From f43fa301c1a2817239e046a242902af65b7cac71 Mon Sep 17 00:00:00 2001 From: Eduard Baturin Date: Sat, 18 Feb 2023 09:43:59 +0300 Subject: fix(lsp): check if the buffer is a directory before w! it (#22289) --- runtime/lua/vim/lsp/util.lua | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 38051e6410..4beb4fc367 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -759,9 +759,11 @@ function M.rename(old_fname, new_fname, opts) vim.fn.bufload(oldbuf) -- The there may be pending changes in the buffer - api.nvim_buf_call(oldbuf, function() - vim.cmd('w!') - end) + if vim.fn.isdirectory(old_fname) == 0 then + api.nvim_buf_call(oldbuf, function() + vim.cmd('w!') + end) + end local ok, err = os.rename(old_fname, new_fname) assert(ok, err) -- cgit From f140175564001cc1ad84128a0147a5d2f7798a63 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Thu, 23 Feb 2023 13:35:46 +0100 Subject: refactor(lsp): remove workaround for missing bit module (#22373) --- runtime/lua/vim/lsp/semantic_tokens.lua | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index b1bc48dac6..00b4757ea9 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -1,6 +1,7 @@ local api = vim.api local handlers = require('vim.lsp.handlers') local util = require('vim.lsp.util') +local bit = require('bit') --- @class STTokenRange --- @field line number line number 0-based @@ -58,18 +59,10 @@ local function modifiers_from_number(x, modifiers_table) local modifiers = {} local idx = 1 while x > 0 do - if _G.bit then - if _G.bit.band(x, 1) == 1 then - modifiers[#modifiers + 1] = modifiers_table[idx] - end - x = _G.bit.rshift(x, 1) - else - --TODO(jdrouhard): remove this branch once `bit` module is available for non-LuaJIT (#21222) - if x % 2 == 1 then - modifiers[#modifiers + 1] = modifiers_table[idx] - end - x = math.floor(x / 2) + if bit.band(x, 1) == 1 then + modifiers[#modifiers + 1] = modifiers_table[idx] end + x = bit.rshift(x, 1) idx = idx + 1 end -- cgit From 5732aa706c639b3d775573d91d1139f24624629c Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Sat, 25 Feb 2023 03:07:18 -0600 Subject: feat(lsp): implement workspace/didChangeWatchedFiles (#21293) --- runtime/lua/vim/lsp/_watchfiles.lua | 274 ++++++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/handlers.lua | 38 +++-- runtime/lua/vim/lsp/protocol.lua | 9 ++ 3 files changed, 312 insertions(+), 9 deletions(-) create mode 100644 runtime/lua/vim/lsp/_watchfiles.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua new file mode 100644 index 0000000000..b9268b963c --- /dev/null +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -0,0 +1,274 @@ +local bit = require('bit') +local watch = require('vim._watch') +local protocol = require('vim.lsp.protocol') + +local M = {} + +---@private +---Parses the raw pattern into a number of Lua-native patterns. +--- +---@param pattern string The raw glob pattern +---@return table A list of Lua patterns. A match with any of them matches the input glob pattern. +local function parse(pattern) + local patterns = { '' } + + local path_sep = '[/\\]' + local non_path_sep = '[^/\\]' + + local function append(chunks) + local new_patterns = {} + for _, p in ipairs(patterns) do + for _, chunk in ipairs(chunks) do + table.insert(new_patterns, p .. chunk) + end + end + patterns = new_patterns + end + + local function split(s, sep) + local segments = {} + local segment = '' + local in_braces = false + local in_brackets = false + for i = 1, #s do + local c = string.sub(s, i, i) + if c == sep and not in_braces and not in_brackets then + table.insert(segments, segment) + segment = '' + else + if c == '{' then + in_braces = true + elseif c == '}' then + in_braces = false + elseif c == '[' then + in_brackets = true + elseif c == ']' then + in_brackets = false + end + segment = segment .. c + end + end + if segment ~= '' then + table.insert(segments, segment) + end + return segments + end + + local function escape(c) + if + c == '?' + or c == '.' + or c == '(' + or c == ')' + or c == '%' + or c == '[' + or c == ']' + or c == '*' + or c == '+' + or c == '-' + then + return '%' .. c + end + return c + end + + local segments = split(pattern, '/') + for i, segment in ipairs(segments) do + local last_seg = i == #segments + if segment == '**' then + local chunks = { + path_sep .. '-', + '.-' .. path_sep, + } + if last_seg then + chunks = { '.-' } + end + append(chunks) + else + local in_braces = false + local brace_val = '' + local in_brackets = false + local bracket_val = '' + for j = 1, #segment do + local char = string.sub(segment, j, j) + if char ~= '}' and in_braces then + brace_val = brace_val .. char + else + if in_brackets and (char ~= ']' or bracket_val == '') then + local res + if char == '-' then + res = char + elseif bracket_val == '' and char == '!' then + res = '^' + elseif char == '/' then + res = '' + else + res = escape(char) + end + bracket_val = bracket_val .. res + else + if char == '{' then + in_braces = true + elseif char == '[' then + in_brackets = true + elseif char == '}' then + local choices = split(brace_val, ',') + local parsed_choices = {} + for _, choice in ipairs(choices) do + table.insert(parsed_choices, parse(choice)) + end + append(vim.tbl_flatten(parsed_choices)) + in_braces = false + brace_val = '' + elseif char == ']' then + append({ '[' .. bracket_val .. ']' }) + in_brackets = false + bracket_val = '' + elseif char == '?' then + append({ non_path_sep }) + elseif char == '*' then + append({ non_path_sep .. '-' }) + else + append({ escape(char) }) + end + end + end + end + + if not last_seg and (segments[i + 1] ~= '**' or i + 1 < #segments) then + append({ path_sep }) + end + end + end + + return patterns +end + +---@private +--- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern +--- Modeled after VSCode's implementation: https://github.com/microsoft/vscode/blob/0319eed971719ad48e9093daba9d65a5013ec5ab/src/vs/base/common/glob.ts#L509 +--- +---@param pattern string|table The glob pattern (raw or parsed) to match. +---@param s string The string to match against pattern. +---@return boolean Whether or not pattern matches s. +function M._match(pattern, s) + if type(pattern) == 'string' then + pattern = parse(pattern) + end + -- Since Lua's built-in string pattern matching does not have an alternate + -- operator like '|', `parse` will construct one pattern for each possible + -- alternative. Any pattern that matches thus matches the glob. + for _, p in ipairs(pattern) do + if s:match('^' .. p .. '$') then + return true + end + end + return false +end + +M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll + +---@type table> client id -> registration id -> cancel function +local cancels = vim.defaulttable() + +local queue_timeout_ms = 100 +---@type table client id -> libuv timer which will send queued changes at its timeout +local queue_timers = {} +---@type table client id -> set of queued changes to send in a single LSP notification +local change_queues = {} +---@type table> client id -> URI -> last type of change processed +--- Used to prune consecutive events of the same type for the same file +local change_cache = vim.defaulttable() + +local to_lsp_change_type = { + [watch.FileChangeType.Created] = protocol.FileChangeType.Created, + [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, + [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted, +} + +--- Registers the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param reg table LSP Registration object. +---@param ctx table Context from the |lsp-handler|. +function M.register(reg, ctx) + local client_id = ctx.client_id + local client = vim.lsp.get_client_by_id(client_id) + for _, w in ipairs(reg.registerOptions.watchers) do + local glob_patterns = {} + if type(w.globPattern) == 'string' then + for _, folder in ipairs(client.workspace_folders) do + table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) + end + else + table.insert(glob_patterns, w.globPattern) + end + for _, glob_pattern in ipairs(glob_patterns) do + local pattern = parse(glob_pattern.pattern) + local base_dir = nil + if type(glob_pattern.baseUri) == 'string' then + base_dir = glob_pattern.baseUri + elseif type(glob_pattern.baseUri) == 'table' then + base_dir = glob_pattern.baseUri.uri + end + assert(base_dir, "couldn't identify root of watch") + base_dir = vim.uri_to_fname(base_dir) + local kind = w.kind + or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete + + table.insert( + cancels[client_id][reg.id], + M._watchfunc(base_dir, { uvflags = { recursive = true } }, function(fullpath, change_type) + change_type = to_lsp_change_type[change_type] + -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) + local kind_mask = bit.lshift(1, change_type - 1) + local change_type_match = bit.band(kind, kind_mask) == kind_mask + if not M._match(pattern, fullpath) or not change_type_match then + return + end + + local change = { + uri = vim.uri_from_fname(fullpath), + type = change_type, + } + + local last_type = change_cache[client_id][change.uri] + if last_type ~= change.type then + change_queues[client_id] = change_queues[client_id] or {} + table.insert(change_queues[client_id], change) + change_cache[client_id][change.uri] = change.type + end + + if not queue_timers[client_id] then + queue_timers[client_id] = vim.defer_fn(function() + client.notify('workspace/didChangeWatchedFiles', { + changes = change_queues[client_id], + }) + queue_timers[client_id] = nil + change_queues[client_id] = nil + change_cache[client_id] = nil + end, queue_timeout_ms) + end + end) + ) + end + end +end + +--- Unregisters the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param unreg table LSP Unregistration object. +---@param ctx table Context from the |lsp-handler|. +function M.unregister(unreg, ctx) + local client_id = ctx.client_id + local client_cancels = cancels[client_id] + local reg_cancels = client_cancels[unreg.id] + while #reg_cancels > 0 do + table.remove(reg_cancels)() + end + client_cancels[unreg.id] = nil + if not next(cancels[client_id]) then + cancels[client_id] = nil + end +end + +return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 5096100a60..ee5b63d260 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -117,15 +117,35 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, _, ctx) - local client_id = ctx.client_id - local warning_tpl = 'The language server %s triggers a registerCapability ' - .. 'handler despite dynamicRegistration set to false. ' - .. 'Report upstream, this warning is harmless' - local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) - local warning = string.format(warning_tpl, client_name) - log.warn(warning) +M['client/registerCapability'] = function(_, result, ctx) + local log_unsupported = false + for _, reg in ipairs(result.registrations) do + if reg.method == 'workspace/didChangeWatchedFiles' then + require('vim.lsp._watchfiles').register(reg, ctx) + else + log_unsupported = true + end + end + if log_unsupported then + local client_id = ctx.client_id + local warning_tpl = 'The language server %s triggers a registerCapability ' + .. 'handler despite dynamicRegistration set to false. ' + .. 'Report upstream, this warning is harmless' + local client = vim.lsp.get_client_by_id(client_id) + local client_name = client and client.name or string.format('id=%d', client_id) + local warning = string.format(warning_tpl, client_name) + log.warn(warning) + end + return vim.NIL +end + +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability +M['client/unregisterCapability'] = function(_, result, ctx) + for _, unreg in ipairs(result.unregisterations) do + if unreg.method == 'workspace/didChangeWatchedFiles' then + require('vim.lsp._watchfiles').unregister(unreg, ctx) + end + end return vim.NIL end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 12345b6c8c..df1ab26667 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -28,6 +28,10 @@ end ---@class lsp.MessageActionItem ---@field title string +---@class lsp.FileEvent +---@field uri string +---@field type lsp.FileChangeType + local constants = { DiagnosticSeverity = { -- Reports an error. @@ -60,6 +64,7 @@ local constants = { }, -- The file event type. + ---@enum lsp.FileChangeType FileChangeType = { -- The file got created. Created = 1, @@ -841,6 +846,10 @@ function protocol.make_client_capabilities() semanticTokens = { refreshSupport = true, }, + didChangeWatchedFiles = { + dynamicRegistration = true, + relativePatternSupport = true, + }, }, experimental = nil, window = { -- cgit From f0f27e9aef7c237dd55fbb5c2cd47c2f42d01742 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Sat, 25 Feb 2023 11:17:28 +0100 Subject: Revert "feat(lsp): implement workspace/didChangeWatchedFiles (#21293)" This reverts commit 5732aa706c639b3d775573d91d1139f24624629c. Causes editor to freeze in projects with many watcher registrations --- runtime/lua/vim/lsp/_watchfiles.lua | 274 ------------------------------------ runtime/lua/vim/lsp/handlers.lua | 38 ++--- runtime/lua/vim/lsp/protocol.lua | 9 -- 3 files changed, 9 insertions(+), 312 deletions(-) delete mode 100644 runtime/lua/vim/lsp/_watchfiles.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua deleted file mode 100644 index b9268b963c..0000000000 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ /dev/null @@ -1,274 +0,0 @@ -local bit = require('bit') -local watch = require('vim._watch') -local protocol = require('vim.lsp.protocol') - -local M = {} - ----@private ----Parses the raw pattern into a number of Lua-native patterns. ---- ----@param pattern string The raw glob pattern ----@return table A list of Lua patterns. A match with any of them matches the input glob pattern. -local function parse(pattern) - local patterns = { '' } - - local path_sep = '[/\\]' - local non_path_sep = '[^/\\]' - - local function append(chunks) - local new_patterns = {} - for _, p in ipairs(patterns) do - for _, chunk in ipairs(chunks) do - table.insert(new_patterns, p .. chunk) - end - end - patterns = new_patterns - end - - local function split(s, sep) - local segments = {} - local segment = '' - local in_braces = false - local in_brackets = false - for i = 1, #s do - local c = string.sub(s, i, i) - if c == sep and not in_braces and not in_brackets then - table.insert(segments, segment) - segment = '' - else - if c == '{' then - in_braces = true - elseif c == '}' then - in_braces = false - elseif c == '[' then - in_brackets = true - elseif c == ']' then - in_brackets = false - end - segment = segment .. c - end - end - if segment ~= '' then - table.insert(segments, segment) - end - return segments - end - - local function escape(c) - if - c == '?' - or c == '.' - or c == '(' - or c == ')' - or c == '%' - or c == '[' - or c == ']' - or c == '*' - or c == '+' - or c == '-' - then - return '%' .. c - end - return c - end - - local segments = split(pattern, '/') - for i, segment in ipairs(segments) do - local last_seg = i == #segments - if segment == '**' then - local chunks = { - path_sep .. '-', - '.-' .. path_sep, - } - if last_seg then - chunks = { '.-' } - end - append(chunks) - else - local in_braces = false - local brace_val = '' - local in_brackets = false - local bracket_val = '' - for j = 1, #segment do - local char = string.sub(segment, j, j) - if char ~= '}' and in_braces then - brace_val = brace_val .. char - else - if in_brackets and (char ~= ']' or bracket_val == '') then - local res - if char == '-' then - res = char - elseif bracket_val == '' and char == '!' then - res = '^' - elseif char == '/' then - res = '' - else - res = escape(char) - end - bracket_val = bracket_val .. res - else - if char == '{' then - in_braces = true - elseif char == '[' then - in_brackets = true - elseif char == '}' then - local choices = split(brace_val, ',') - local parsed_choices = {} - for _, choice in ipairs(choices) do - table.insert(parsed_choices, parse(choice)) - end - append(vim.tbl_flatten(parsed_choices)) - in_braces = false - brace_val = '' - elseif char == ']' then - append({ '[' .. bracket_val .. ']' }) - in_brackets = false - bracket_val = '' - elseif char == '?' then - append({ non_path_sep }) - elseif char == '*' then - append({ non_path_sep .. '-' }) - else - append({ escape(char) }) - end - end - end - end - - if not last_seg and (segments[i + 1] ~= '**' or i + 1 < #segments) then - append({ path_sep }) - end - end - end - - return patterns -end - ----@private ---- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern ---- Modeled after VSCode's implementation: https://github.com/microsoft/vscode/blob/0319eed971719ad48e9093daba9d65a5013ec5ab/src/vs/base/common/glob.ts#L509 ---- ----@param pattern string|table The glob pattern (raw or parsed) to match. ----@param s string The string to match against pattern. ----@return boolean Whether or not pattern matches s. -function M._match(pattern, s) - if type(pattern) == 'string' then - pattern = parse(pattern) - end - -- Since Lua's built-in string pattern matching does not have an alternate - -- operator like '|', `parse` will construct one pattern for each possible - -- alternative. Any pattern that matches thus matches the glob. - for _, p in ipairs(pattern) do - if s:match('^' .. p .. '$') then - return true - end - end - return false -end - -M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll - ----@type table> client id -> registration id -> cancel function -local cancels = vim.defaulttable() - -local queue_timeout_ms = 100 ----@type table client id -> libuv timer which will send queued changes at its timeout -local queue_timers = {} ----@type table client id -> set of queued changes to send in a single LSP notification -local change_queues = {} ----@type table> client id -> URI -> last type of change processed ---- Used to prune consecutive events of the same type for the same file -local change_cache = vim.defaulttable() - -local to_lsp_change_type = { - [watch.FileChangeType.Created] = protocol.FileChangeType.Created, - [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, - [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted, -} - ---- Registers the workspace/didChangeWatchedFiles capability dynamically. ---- ----@param reg table LSP Registration object. ----@param ctx table Context from the |lsp-handler|. -function M.register(reg, ctx) - local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) - for _, w in ipairs(reg.registerOptions.watchers) do - local glob_patterns = {} - if type(w.globPattern) == 'string' then - for _, folder in ipairs(client.workspace_folders) do - table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) - end - else - table.insert(glob_patterns, w.globPattern) - end - for _, glob_pattern in ipairs(glob_patterns) do - local pattern = parse(glob_pattern.pattern) - local base_dir = nil - if type(glob_pattern.baseUri) == 'string' then - base_dir = glob_pattern.baseUri - elseif type(glob_pattern.baseUri) == 'table' then - base_dir = glob_pattern.baseUri.uri - end - assert(base_dir, "couldn't identify root of watch") - base_dir = vim.uri_to_fname(base_dir) - local kind = w.kind - or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete - - table.insert( - cancels[client_id][reg.id], - M._watchfunc(base_dir, { uvflags = { recursive = true } }, function(fullpath, change_type) - change_type = to_lsp_change_type[change_type] - -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) - local kind_mask = bit.lshift(1, change_type - 1) - local change_type_match = bit.band(kind, kind_mask) == kind_mask - if not M._match(pattern, fullpath) or not change_type_match then - return - end - - local change = { - uri = vim.uri_from_fname(fullpath), - type = change_type, - } - - local last_type = change_cache[client_id][change.uri] - if last_type ~= change.type then - change_queues[client_id] = change_queues[client_id] or {} - table.insert(change_queues[client_id], change) - change_cache[client_id][change.uri] = change.type - end - - if not queue_timers[client_id] then - queue_timers[client_id] = vim.defer_fn(function() - client.notify('workspace/didChangeWatchedFiles', { - changes = change_queues[client_id], - }) - queue_timers[client_id] = nil - change_queues[client_id] = nil - change_cache[client_id] = nil - end, queue_timeout_ms) - end - end) - ) - end - end -end - ---- Unregisters the workspace/didChangeWatchedFiles capability dynamically. ---- ----@param unreg table LSP Unregistration object. ----@param ctx table Context from the |lsp-handler|. -function M.unregister(unreg, ctx) - local client_id = ctx.client_id - local client_cancels = cancels[client_id] - local reg_cancels = client_cancels[unreg.id] - while #reg_cancels > 0 do - table.remove(reg_cancels)() - end - client_cancels[unreg.id] = nil - if not next(cancels[client_id]) then - cancels[client_id] = nil - end -end - -return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index ee5b63d260..5096100a60 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -117,35 +117,15 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, result, ctx) - local log_unsupported = false - for _, reg in ipairs(result.registrations) do - if reg.method == 'workspace/didChangeWatchedFiles' then - require('vim.lsp._watchfiles').register(reg, ctx) - else - log_unsupported = true - end - end - if log_unsupported then - local client_id = ctx.client_id - local warning_tpl = 'The language server %s triggers a registerCapability ' - .. 'handler despite dynamicRegistration set to false. ' - .. 'Report upstream, this warning is harmless' - local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) - local warning = string.format(warning_tpl, client_name) - log.warn(warning) - end - return vim.NIL -end - ---see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability -M['client/unregisterCapability'] = function(_, result, ctx) - for _, unreg in ipairs(result.unregisterations) do - if unreg.method == 'workspace/didChangeWatchedFiles' then - require('vim.lsp._watchfiles').unregister(unreg, ctx) - end - end +M['client/registerCapability'] = function(_, _, ctx) + local client_id = ctx.client_id + local warning_tpl = 'The language server %s triggers a registerCapability ' + .. 'handler despite dynamicRegistration set to false. ' + .. 'Report upstream, this warning is harmless' + local client = vim.lsp.get_client_by_id(client_id) + local client_name = client and client.name or string.format('id=%d', client_id) + local warning = string.format(warning_tpl, client_name) + log.warn(warning) return vim.NIL end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index df1ab26667..12345b6c8c 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -28,10 +28,6 @@ end ---@class lsp.MessageActionItem ---@field title string ----@class lsp.FileEvent ----@field uri string ----@field type lsp.FileChangeType - local constants = { DiagnosticSeverity = { -- Reports an error. @@ -64,7 +60,6 @@ local constants = { }, -- The file event type. - ---@enum lsp.FileChangeType FileChangeType = { -- The file got created. Created = 1, @@ -846,10 +841,6 @@ function protocol.make_client_capabilities() semanticTokens = { refreshSupport = true, }, - didChangeWatchedFiles = { - dynamicRegistration = true, - relativePatternSupport = true, - }, }, experimental = nil, window = { -- cgit From c1514d7e6762ed62dee027ecc29bafd4aae2206e Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sat, 25 Feb 2023 18:47:05 +0100 Subject: fix(lsp): fix some type annotations (#22397) --- runtime/lua/vim/lsp/protocol.lua | 9 +-------- runtime/lua/vim/lsp/rpc.lua | 8 ++++---- runtime/lua/vim/lsp/types.lua | 20 ++++++++++++++++++++ 3 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 runtime/lua/vim/lsp/types.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 12345b6c8c..41dfc9e00e 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -20,14 +20,6 @@ function transform_schema_to_table() end --]=] ----@class lsp.ShowMessageRequestParams ----@field type lsp.MessageType ----@field message string ----@field actions nil|lsp.MessageActionItem[] - ----@class lsp.MessageActionItem ----@field title string - local constants = { DiagnosticSeverity = { -- Reports an error. @@ -60,6 +52,7 @@ local constants = { }, -- The file event type. + ---@enum lsp.FileChangeType FileChangeType = { -- The file got created. Created = 1, diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index f1492601ff..aa833deb99 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -319,9 +319,9 @@ end --- ---@param method (string) The invoked LSP method ---@param params (table|nil) Parameters for the invoked LSP method ----@param callback (function) Callback to invoke +---@param callback fun(err: lsp.ResponseError|nil, result: any) Callback to invoke ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending ----@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not +---@return boolean success, integer|nil request_id true, request_id if request could be sent, `false` if not function Client:request(method, params, callback, notify_reply_callback) validate({ callback = { callback, 'f' }, @@ -538,9 +538,9 @@ local function public_client(client) --- ---@param method (string) The invoked LSP method ---@param params (table|nil) Parameters for the invoked LSP method - ---@param callback (function) Callback to invoke + ---@param callback fun(err: lsp.ResponseError | nil, result: any) Callback to invoke ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending - ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not + ---@return boolean success, integer|nil request_id true, message_id if request could be sent, `false` if not function result.request(method, params, callback, notify_reply_callback) return client:request(method, params, callback, notify_reply_callback) end diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua new file mode 100644 index 0000000000..1aea6841ee --- /dev/null +++ b/runtime/lua/vim/lsp/types.lua @@ -0,0 +1,20 @@ +---@meta + +---@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: table, config: table|nil) + +---@class lsp.ResponseError +---@field code integer +---@field message string +---@field data string|number|boolean|table[]|table|nil + +---@class lsp.ShowMessageRequestParams +---@field type lsp.MessageType +---@field message string +---@field actions nil|lsp.MessageActionItem[] + +---@class lsp.MessageActionItem +---@field title string + +---@class lsp.FileEvent +---@field uri string +---@field type lsp.FileChangeType -- cgit From 7e19cabeb192d2e7f20d7bb965a3f62e1543d2ac Mon Sep 17 00:00:00 2001 From: bfredl Date: Tue, 28 Feb 2023 12:38:33 +0100 Subject: perf(lsp): only redraw the windows containing LSP tokens redraw! redraws the entire screen instead of just the windows with the buffer which were actually changed. I considered trying to calculating the range for the delta but it looks tricky. Could a follow-up. --- runtime/lua/vim/lsp/semantic_tokens.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 00b4757ea9..24b5c6c24e 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -334,7 +334,8 @@ function STHighlighter:process_response(response, client, version) current_result.highlights = tokens_to_ranges(tokens, self.bufnr, client) current_result.namespace_cleared = false - api.nvim_command('redraw!') + -- redraw all windows displaying buffer + api.nvim__buf_redraw_range(self.bufnr, 0, -1) end --- on_win handler for the decoration provider (see |nvim_set_decoration_provider|) -- cgit From 896d672736b32a8f4a4fa51844b44f266dcdcc6c Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Wed, 1 Mar 2023 15:33:13 +0100 Subject: fix(lsp): use buffer scheme for files not stored on disk (#22407) Sending `didOpen` with a `file` scheme causes problems with some language servers because they expect the file to exist on disk. See https://github.com/microsoft/language-server-protocol/pull/1679 --- runtime/lua/vim/lsp/util.lua | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 4beb4fc367..554e26022c 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2032,7 +2032,12 @@ end ---@returns `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params(bufnr) - return { uri = vim.uri_from_bufnr(bufnr or 0) } + bufnr = bufnr or 0 + local uri = vim.uri_from_bufnr(bufnr) + if not uv.fs_stat(api.nvim_buf_get_name(bufnr)) then + uri = uri:gsub('^file://', 'buffer://') + end + return { uri = uri } end --- Create the workspace params @@ -2065,7 +2070,7 @@ function M.make_formatting_params(options) insertSpaces = vim.bo.expandtab, }) return { - textDocument = { uri = vim.uri_from_bufnr(0) }, + textDocument = M.make_text_document_params(0), options = options, } end -- cgit From ac69ba5fa0081026f2c5e6e29d5788802479b7b9 Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Sun, 5 Mar 2023 00:52:27 -0600 Subject: feat(lsp): implement workspace/didChangeWatchedFiles (#22405) --- runtime/lua/vim/lsp/_watchfiles.lua | 293 ++++++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/handlers.lua | 38 +++-- runtime/lua/vim/lsp/protocol.lua | 4 + 3 files changed, 326 insertions(+), 9 deletions(-) create mode 100644 runtime/lua/vim/lsp/_watchfiles.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua new file mode 100644 index 0000000000..96d7fa1d35 --- /dev/null +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -0,0 +1,293 @@ +local bit = require('bit') +local watch = require('vim._watch') +local protocol = require('vim.lsp.protocol') + +local M = {} + +---@private +---Parses the raw pattern into a number of Lua-native patterns. +--- +---@param pattern string The raw glob pattern +---@return table A list of Lua patterns. A match with any of them matches the input glob pattern. +local function parse(pattern) + local patterns = { '' } + + local path_sep = '[/\\]' + local non_path_sep = '[^/\\]' + + local function append(chunks) + local new_patterns = {} + for _, p in ipairs(patterns) do + for _, chunk in ipairs(chunks) do + table.insert(new_patterns, p .. chunk) + end + end + patterns = new_patterns + end + + local function split(s, sep) + local segments = {} + local segment = '' + local in_braces = false + local in_brackets = false + for i = 1, #s do + local c = string.sub(s, i, i) + if c == sep and not in_braces and not in_brackets then + table.insert(segments, segment) + segment = '' + else + if c == '{' then + in_braces = true + elseif c == '}' then + in_braces = false + elseif c == '[' then + in_brackets = true + elseif c == ']' then + in_brackets = false + end + segment = segment .. c + end + end + if segment ~= '' then + table.insert(segments, segment) + end + return segments + end + + local function escape(c) + if + c == '?' + or c == '.' + or c == '(' + or c == ')' + or c == '%' + or c == '[' + or c == ']' + or c == '*' + or c == '+' + or c == '-' + then + return '%' .. c + end + return c + end + + local segments = split(pattern, '/') + for i, segment in ipairs(segments) do + local last_seg = i == #segments + if segment == '**' then + local chunks = { + path_sep .. '-', + '.-' .. path_sep, + } + if last_seg then + chunks = { '.-' } + end + append(chunks) + else + local in_braces = false + local brace_val = '' + local in_brackets = false + local bracket_val = '' + for j = 1, #segment do + local char = string.sub(segment, j, j) + if char ~= '}' and in_braces then + brace_val = brace_val .. char + else + if in_brackets and (char ~= ']' or bracket_val == '') then + local res + if char == '-' then + res = char + elseif bracket_val == '' and char == '!' then + res = '^' + elseif char == '/' then + res = '' + else + res = escape(char) + end + bracket_val = bracket_val .. res + else + if char == '{' then + in_braces = true + elseif char == '[' then + in_brackets = true + elseif char == '}' then + local choices = split(brace_val, ',') + local parsed_choices = {} + for _, choice in ipairs(choices) do + table.insert(parsed_choices, parse(choice)) + end + append(vim.tbl_flatten(parsed_choices)) + in_braces = false + brace_val = '' + elseif char == ']' then + append({ '[' .. bracket_val .. ']' }) + in_brackets = false + bracket_val = '' + elseif char == '?' then + append({ non_path_sep }) + elseif char == '*' then + append({ non_path_sep .. '-' }) + else + append({ escape(char) }) + end + end + end + end + + if not last_seg and (segments[i + 1] ~= '**' or i + 1 < #segments) then + append({ path_sep }) + end + end + end + + return patterns +end + +---@private +--- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern +--- Modeled after VSCode's implementation: https://github.com/microsoft/vscode/blob/0319eed971719ad48e9093daba9d65a5013ec5ab/src/vs/base/common/glob.ts#L509 +--- +---@param pattern string|table The glob pattern (raw or parsed) to match. +---@param s string The string to match against pattern. +---@return boolean Whether or not pattern matches s. +function M._match(pattern, s) + if type(pattern) == 'string' then + pattern = parse(pattern) + end + -- Since Lua's built-in string pattern matching does not have an alternate + -- operator like '|', `parse` will construct one pattern for each possible + -- alternative. Any pattern that matches thus matches the glob. + for _, p in ipairs(pattern) do + if s:match('^' .. p .. '$') then + return true + end + end + return false +end + +M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll + +---@type table> client id -> registration id -> cancel function +local cancels = vim.defaulttable() + +local queue_timeout_ms = 100 +---@type table client id -> libuv timer which will send queued changes at its timeout +local queue_timers = {} +---@type table client id -> set of queued changes to send in a single LSP notification +local change_queues = {} +---@type table> client id -> URI -> last type of change processed +--- Used to prune consecutive events of the same type for the same file +local change_cache = vim.defaulttable() + +local to_lsp_change_type = { + [watch.FileChangeType.Created] = protocol.FileChangeType.Created, + [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, + [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted, +} + +--- Registers the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param reg table LSP Registration object. +---@param ctx table Context from the |lsp-handler|. +function M.register(reg, ctx) + local client_id = ctx.client_id + local client = vim.lsp.get_client_by_id(client_id) + local watch_regs = {} + for _, w in ipairs(reg.registerOptions.watchers) do + local glob_patterns = {} + if type(w.globPattern) == 'string' then + for _, folder in ipairs(client.workspace_folders) do + table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) + end + else + table.insert(glob_patterns, w.globPattern) + end + for _, glob_pattern in ipairs(glob_patterns) do + local pattern = parse(glob_pattern.pattern) + local base_dir = nil + if type(glob_pattern.baseUri) == 'string' then + base_dir = glob_pattern.baseUri + elseif type(glob_pattern.baseUri) == 'table' then + base_dir = glob_pattern.baseUri.uri + end + assert(base_dir, "couldn't identify root of watch") + base_dir = vim.uri_to_fname(base_dir) + local kind = w.kind + or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete + + table.insert(watch_regs, { + base_dir = base_dir, + pattern = pattern, + kind = kind, + }) + end + end + + local callback = function(base_dir) + return function(fullpath, change_type) + for _, w in ipairs(watch_regs) do + change_type = to_lsp_change_type[change_type] + -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) + local kind_mask = bit.lshift(1, change_type - 1) + local change_type_match = bit.band(w.kind, kind_mask) == kind_mask + if base_dir == w.base_dir and M._match(w.pattern, fullpath) and change_type_match then + local change = { + uri = vim.uri_from_fname(fullpath), + type = change_type, + } + + local last_type = change_cache[client_id][change.uri] + if last_type ~= change.type then + change_queues[client_id] = change_queues[client_id] or {} + table.insert(change_queues[client_id], change) + change_cache[client_id][change.uri] = change.type + end + + if not queue_timers[client_id] then + queue_timers[client_id] = vim.defer_fn(function() + client.notify('workspace/didChangeWatchedFiles', { + changes = change_queues[client_id], + }) + queue_timers[client_id] = nil + change_queues[client_id] = nil + change_cache[client_id] = nil + end, queue_timeout_ms) + end + + break -- if an event matches multiple watchers, only send one notification + end + end + end + end + + local watching = {} + for _, w in ipairs(watch_regs) do + if not watching[w.base_dir] then + watching[w.base_dir] = true + table.insert( + cancels[client_id][reg.id], + M._watchfunc(w.base_dir, { uvflags = { recursive = true } }, callback(w.base_dir)) + ) + end + end +end + +--- Unregisters the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param unreg table LSP Unregistration object. +---@param ctx table Context from the |lsp-handler|. +function M.unregister(unreg, ctx) + local client_id = ctx.client_id + local client_cancels = cancels[client_id] + local reg_cancels = client_cancels[unreg.id] + while #reg_cancels > 0 do + table.remove(reg_cancels)() + end + client_cancels[unreg.id] = nil + if not next(cancels[client_id]) then + cancels[client_id] = nil + end +end + +return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 5096100a60..ee5b63d260 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -117,15 +117,35 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, _, ctx) - local client_id = ctx.client_id - local warning_tpl = 'The language server %s triggers a registerCapability ' - .. 'handler despite dynamicRegistration set to false. ' - .. 'Report upstream, this warning is harmless' - local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) - local warning = string.format(warning_tpl, client_name) - log.warn(warning) +M['client/registerCapability'] = function(_, result, ctx) + local log_unsupported = false + for _, reg in ipairs(result.registrations) do + if reg.method == 'workspace/didChangeWatchedFiles' then + require('vim.lsp._watchfiles').register(reg, ctx) + else + log_unsupported = true + end + end + if log_unsupported then + local client_id = ctx.client_id + local warning_tpl = 'The language server %s triggers a registerCapability ' + .. 'handler despite dynamicRegistration set to false. ' + .. 'Report upstream, this warning is harmless' + local client = vim.lsp.get_client_by_id(client_id) + local client_name = client and client.name or string.format('id=%d', client_id) + local warning = string.format(warning_tpl, client_name) + log.warn(warning) + end + return vim.NIL +end + +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability +M['client/unregisterCapability'] = function(_, result, ctx) + for _, unreg in ipairs(result.unregisterations) do + if unreg.method == 'workspace/didChangeWatchedFiles' then + require('vim.lsp._watchfiles').unregister(unreg, ctx) + end + end return vim.NIL end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 41dfc9e00e..27dd68645a 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -834,6 +834,10 @@ function protocol.make_client_capabilities() semanticTokens = { refreshSupport = true, }, + didChangeWatchedFiles = { + dynamicRegistration = false, + relativePatternSupport = true, + }, }, experimental = nil, window = { -- cgit From ed05d38d9fa643c7e562b754c6cfed8b9da5c4d8 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sun, 5 Mar 2023 08:42:15 +0100 Subject: fix(lsp): don't monitor files if workspace_folders is nil (#22531) Fixes: Error SERVER_REQUEST_HANDLER_ERROR: "...di/dev/neovim/neovim/runtime/lua/vim/lsp/_watchfiles.lua :200: bad argument #1 to 'ipairs' (table expected, got nil)" Language servers can be started without root_dir or workspace_folders. --- runtime/lua/vim/lsp/_watchfiles.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 96d7fa1d35..533a955925 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -168,11 +168,11 @@ end M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll ----@type table> client id -> registration id -> cancel function +---@type table> client id -> registration id -> cancel function local cancels = vim.defaulttable() local queue_timeout_ms = 100 ----@type table client id -> libuv timer which will send queued changes at its timeout +---@type table client id -> libuv timer which will send queued changes at its timeout local queue_timers = {} ---@type table client id -> set of queued changes to send in a single LSP notification local change_queues = {} @@ -193,6 +193,9 @@ local to_lsp_change_type = { function M.register(reg, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) + if not client.workspace_folders then + return + end local watch_regs = {} for _, w in ipairs(reg.registerOptions.watchers) do local glob_patterns = {} -- cgit From 1cc23e1109ed88275df5c986c352f73b99a0301c Mon Sep 17 00:00:00 2001 From: swarn Date: Mon, 6 Mar 2023 12:03:13 -0600 Subject: feat(lsp)!: add rule-based sem token highlighting (#22022) feat(lsp)!: change semantic token highlighting Change the default highlights used, and add more highlights per token. Add an LspTokenUpdate event and a highlight_token function. :Inspect now shows any highlights applied by token highlighting rules, default or user-defined. BREAKING CHANGE: change the default highlight groups used by semantic token highlighting. --- runtime/lua/vim/lsp/semantic_tokens.lua | 183 ++++++++++++++++++++++---------- 1 file changed, 125 insertions(+), 58 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 24b5c6c24e..7983d066b8 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -8,8 +8,8 @@ local bit = require('bit') --- @field start_col number start column 0-based --- @field end_col number end column 0-based --- @field type string token type as string ---- @field modifiers string[] token modifiers as strings ---- @field extmark_added boolean whether this extmark has been added to the buffer yet +--- @field modifiers table token modifiers as a set. E.g., { static = true, readonly = true } +--- @field marked boolean whether this token has had extmarks applied --- --- @class STCurrentResult --- @field version number document version associated with this result @@ -36,10 +36,13 @@ local bit = require('bit') ---@field client_state table local STHighlighter = { active = {} } +--- Do a binary search of the tokens in the half-open range [lo, hi). +--- +--- Return the index i in range such that tokens[j].line < line for all j < i, and +--- tokens[j].line >= line for all j >= i, or return hi if no such index is found. +--- ---@private -local function binary_search(tokens, line) - local lo = 1 - local hi = #tokens +local function lower_bound(tokens, line, lo, hi) while lo < hi do local mid = math.floor((lo + hi) / 2) if tokens[mid].line < line then @@ -51,16 +54,34 @@ local function binary_search(tokens, line) return lo end +--- Do a binary search of the tokens in the half-open range [lo, hi). +--- +--- Return the index i in range such that tokens[j].line <= line for all j < i, and +--- tokens[j].line > line for all j >= i, or return hi if no such index is found. +--- +---@private +local function upper_bound(tokens, line, lo, hi) + while lo < hi do + local mid = math.floor((lo + hi) / 2) + if line < tokens[mid].line then + hi = mid + else + lo = mid + 1 + end + end + return lo +end + --- Extracts modifier strings from the encoded number in the token array --- ---@private ----@return string[] +---@return table local function modifiers_from_number(x, modifiers_table) local modifiers = {} local idx = 1 while x > 0 do if bit.band(x, 1) == 1 then - modifiers[#modifiers + 1] = modifiers_table[idx] + modifiers[modifiers_table[idx]] = true end x = bit.rshift(x, 1) idx = idx + 1 @@ -109,7 +130,7 @@ local function tokens_to_ranges(data, bufnr, client) end_col = end_col, type = token_type, modifiers = modifiers, - extmark_added = false, + marked = false, } end end @@ -355,7 +376,7 @@ end --- ---@private function STHighlighter:on_win(topline, botline) - for _, state in pairs(self.client_state) do + for client_id, state in pairs(self.client_state) do local current_result = state.current_result if current_result.version and current_result.version == util.buf_versions[self.bufnr] then if not current_result.namespace_cleared then @@ -372,52 +393,55 @@ function STHighlighter:on_win(topline, botline) -- -- Instead, we have to use normal extmarks that can attach to locations -- in the buffer and are persisted between redraws. + -- + -- `strict = false` is necessary here for the 1% of cases where the + -- current result doesn't actually match the buffer contents. Some + -- LSP servers can respond with stale tokens on requests if they are + -- still processing changes from a didChange notification. + -- + -- LSP servers that do this _should_ follow up known stale responses + -- with a refresh notification once they've finished processing the + -- didChange notification, which would re-synchronize the tokens from + -- our end. + -- + -- The server I know of that does this is clangd when the preamble of + -- a file changes and the token request is processed with a stale + -- preamble while the new one is still being built. Once the preamble + -- finishes, clangd sends a refresh request which lets the client + -- re-synchronize the tokens. + + local set_mark = function(token, hl_group, delta) + vim.api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { + hl_group = hl_group, + end_col = token.end_col, + priority = vim.highlight.priorities.semantic_tokens + delta, + strict = false, + }) + end + + local ft = vim.bo[self.bufnr].filetype local highlights = current_result.highlights - local idx = binary_search(highlights, topline) + local first = lower_bound(highlights, topline, 1, #highlights + 1) + local last = upper_bound(highlights, botline, first, #highlights + 1) - 1 - for i = idx, #highlights do + for i = first, last do local token = highlights[i] - - if token.line > botline then - break - end - - if not token.extmark_added then - -- `strict = false` is necessary here for the 1% of cases where the - -- current result doesn't actually match the buffer contents. Some - -- LSP servers can respond with stale tokens on requests if they are - -- still processing changes from a didChange notification. - -- - -- LSP servers that do this _should_ follow up known stale responses - -- with a refresh notification once they've finished processing the - -- didChange notification, which would re-synchronize the tokens from - -- our end. - -- - -- The server I know of that does this is clangd when the preamble of - -- a file changes and the token request is processed with a stale - -- preamble while the new one is still being built. Once the preamble - -- finishes, clangd sends a refresh request which lets the client - -- re-synchronize the tokens. - api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { - hl_group = '@' .. token.type, - end_col = token.end_col, - priority = vim.highlight.priorities.semantic_tokens, - strict = false, - }) - - -- TODO(bfredl) use single extmark when hl_group supports table - if #token.modifiers > 0 then - for _, modifier in pairs(token.modifiers) do - api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { - hl_group = '@' .. modifier, - end_col = token.end_col, - priority = vim.highlight.priorities.semantic_tokens + 1, - strict = false, - }) - end + if not token.marked then + set_mark(token, string.format('@lsp.type.%s.%s', token.type, ft), 0) + for modifier, _ in pairs(token.modifiers) do + set_mark(token, string.format('@lsp.mod.%s.%s', modifier, ft), 1) + set_mark(token, string.format('@lsp.typemod.%s.%s.%s', token.type, modifier, ft), 2) end - - token.extmark_added = true + token.marked = true + + api.nvim_exec_autocmds('LspTokenUpdate', { + pattern = vim.api.nvim_buf_get_name(self.bufnr), + modeline = false, + data = { + token = token, + client_id = client_id, + }, + }) end end end @@ -588,7 +612,13 @@ end ---@param row number|nil Position row (default cursor position) ---@param col number|nil Position column (default cursor position) --- ----@return table|nil (table|nil) List of tokens at position +---@return table|nil (table|nil) List of tokens at position. Each token has +--- the following fields: +--- - line (number) line number, 0-based +--- - start_col (number) start column, 0-based +--- - end_col (number) end column, 0-based +--- - type (string) token type as string, e.g. "variable" +--- - modifiers (table) token modifiers as a set. E.g., { static = true, readonly = true } function M.get_at_pos(bufnr, row, col) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() @@ -608,7 +638,7 @@ function M.get_at_pos(bufnr, row, col) for client_id, client in pairs(highlighter.client_state) do local highlights = client.current_result.highlights if highlights then - local idx = binary_search(highlights, row) + local idx = lower_bound(highlights, row, 1, #highlights + 1) for i = idx, #highlights do local token = highlights[i] @@ -631,23 +661,60 @@ end --- Only has an effect if the buffer is currently active for semantic token --- highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) --- ----@param bufnr (nil|number) default: current buffer +---@param bufnr (number|nil) filter by buffer. All buffers if nil, current +--- buffer if 0 function M.force_refresh(bufnr) vim.validate({ bufnr = { bufnr, 'n', true }, }) - if bufnr == nil or bufnr == 0 then - bufnr = api.nvim_get_current_buf() + local buffers = bufnr == nil and vim.tbl_keys(STHighlighter.active) + or bufnr == 0 and { api.nvim_get_current_buf() } + or { bufnr } + + for _, buffer in ipairs(buffers) do + local highlighter = STHighlighter.active[buffer] + if highlighter then + highlighter:reset() + highlighter:send_request() + end end +end +--- Highlight a semantic token. +--- +--- Apply an extmark with a given highlight group for a semantic token. The +--- mark will be deleted by the semantic token engine when appropriate; for +--- example, when the LSP sends updated tokens. This function is intended for +--- use inside |LspTokenUpdate| callbacks. +---@param token (table) a semantic token, found as `args.data.token` in +--- |LspTokenUpdate|. +---@param bufnr (number) the buffer to highlight +---@param client_id (number) The ID of the |vim.lsp.client| +---@param hl_group (string) Highlight group name +---@param opts (table|nil) Optional parameters. +--- - priority: (number|nil) Priority for the applied extmark. Defaults +--- to `vim.highlight.priorities.semantic_tokens + 3` +function M.highlight_token(token, bufnr, client_id, hl_group, opts) local highlighter = STHighlighter.active[bufnr] if not highlighter then return end - highlighter:reset() - highlighter:send_request() + local state = highlighter.client_state[client_id] + if not state then + return + end + + opts = opts or {} + local priority = opts.priority or vim.highlight.priorities.semantic_tokens + 3 + + vim.api.nvim_buf_set_extmark(bufnr, state.namespace, token.line, token.start_col, { + hl_group = hl_group, + end_col = token.end_col, + priority = priority, + strict = false, + }) end --- |lsp-handler| for the method `workspace/semanticTokens/refresh` -- cgit From 706bcab75eaad2c370d61bf828531054439d3a3e Mon Sep 17 00:00:00 2001 From: Jaehwang Jung Date: Tue, 7 Mar 2023 15:17:52 +0900 Subject: docs(lsp): change type annotations from number → integer (#22510) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- runtime/lua/vim/lsp/_snippet.lua | 2 +- runtime/lua/vim/lsp/codelens.lua | 14 +++--- runtime/lua/vim/lsp/diagnostic.lua | 12 +++--- runtime/lua/vim/lsp/log.lua | 4 +- runtime/lua/vim/lsp/rpc.lua | 16 +++---- runtime/lua/vim/lsp/semantic_tokens.lua | 60 +++++++++++++------------- runtime/lua/vim/lsp/sync.lua | 6 +-- runtime/lua/vim/lsp/util.lua | 76 ++++++++++++++++----------------- 8 files changed, 95 insertions(+), 95 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet.lua b/runtime/lua/vim/lsp/_snippet.lua index 3488639fb4..797d8960d5 100644 --- a/runtime/lua/vim/lsp/_snippet.lua +++ b/runtime/lua/vim/lsp/_snippet.lua @@ -483,7 +483,7 @@ end) local M = {} ---The snippet node type enum ----@types table +---@types table M.NodeType = Node.Type ---Parse snippet string and returns the AST diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 17489ed84d..81cac6a511 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -61,7 +61,7 @@ end --- Return all lenses for the given buffer --- ----@param bufnr number Buffer number. 0 can be used for the current buffer. +---@param bufnr integer Buffer number. 0 can be used for the current buffer. ---@return table (`CodeLens[]`) function M.get(bufnr) local lenses_by_client = lens_cache_by_buf[bufnr or 0] @@ -115,8 +115,8 @@ end --- Clear the lenses --- ----@param client_id number|nil filter by client_id. All clients if nil ----@param bufnr number|nil filter by buffer. All buffers if nil +---@param client_id integer|nil filter by client_id. All clients if nil +---@param bufnr integer|nil filter by buffer. All buffers if nil function M.clear(client_id, bufnr) local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(lens_cache_by_buf) for _, iter_bufnr in pairs(buffers) do @@ -132,8 +132,8 @@ end --- Display the lenses using virtual text --- ---@param lenses table of lenses to display (`CodeLens[] | null`) ----@param bufnr number ----@param client_id number +---@param bufnr integer +---@param client_id integer function M.display(lenses, bufnr, client_id) local ns = namespaces[client_id] if not lenses or not next(lenses) then @@ -177,8 +177,8 @@ end --- Store lenses for a specific buffer and client --- ---@param lenses table of lenses to store (`CodeLens[] | null`) ----@param bufnr number ----@param client_id number +---@param bufnr integer +---@param client_id integer function M.save(lenses, bufnr, client_id) local lenses_by_client = lens_cache_by_buf[bufnr] if not lenses_by_client then diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 5e2bf75f1b..b27bf6e425 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -4,7 +4,7 @@ ---@field range Range ---@field message string ---@field severity DiagnosticSeverity|nil ----@field code number | string +---@field code integer | string ---@field source string ---@field tags DiagnosticTag[] ---@field relatedInformation DiagnosticRelatedInformation[] @@ -135,7 +135,7 @@ local _client_namespaces = {} --- Get the diagnostic namespace associated with an LSP client |vim.diagnostic|. --- ----@param client_id number The id of the LSP client +---@param client_id integer The id of the LSP client function M.get_namespace(client_id) vim.validate({ client_id = { client_id, 'n' } }) if not _client_namespaces[client_id] then @@ -212,7 +212,7 @@ end --- this method signature is still used internally in some parts of the LSP --- implementation so it's simply marked @private rather than @deprecated. --- ----@param client_id number +---@param client_id integer ---@param buffer_client_map table map of buffers to active clients ---@private function M.reset(client_id, buffer_client_map) @@ -232,14 +232,14 @@ end --- Marked private as this is used internally by the LSP subsystem, but --- most users should instead prefer |vim.diagnostic.get()|. --- ----@param bufnr number|nil The buffer number ----@param line_nr number|nil The line number +---@param bufnr integer|nil The buffer number +---@param line_nr integer|nil The line number ---@param opts table|nil Configuration keys --- - severity: (DiagnosticSeverity, default nil) --- - Only return diagnostics with this severity. Overrides severity_limit --- - severity_limit: (DiagnosticSeverity, default nil) --- - Limit severity of diagnostics found. E.g. "Warning" means { "Error", "Warning" } will be valid. ----@param client_id|nil number the client id +---@param client_id integer|nil the client id ---@return table Table with map of line number to list of diagnostics. --- Structured: { [1] = {...}, [5] = {.... } } ---@private diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index d1a78572aa..51dcb7d21d 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -141,7 +141,7 @@ end vim.tbl_add_reverse_lookup(log.levels) --- Sets the current log level. ----@param level (string|number) One of `vim.lsp.log.levels` +---@param level (string|integer) One of `vim.lsp.log.levels` function log.set_level(level) if type(level) == 'string' then current_log_level = @@ -167,7 +167,7 @@ function log.set_format_func(handle) end --- Checks whether the level is sufficient for logging. ----@param level number log level +---@param level integer log level ---@returns (bool) true if would log, false if not function log.should_log(level) return level >= current_log_level diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index aa833deb99..30b61d01d6 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -186,7 +186,7 @@ end --- Creates an RPC response object/table. --- ----@param code number RPC error code defined in `vim.lsp.protocol.ErrorCodes` +---@param code integer RPC error code defined in `vim.lsp.protocol.ErrorCodes` ---@param message string|nil arbitrary message to send to server ---@param data any|nil arbitrary data to send to server local function rpc_response_error(code, message, data) @@ -224,8 +224,8 @@ end ---@private --- Default dispatcher for when a client exits. --- ----@param code (number): Exit code ----@param signal (number): Number describing the signal used to terminate (if +---@param code (integer): Exit code +---@param signal (integer): Number describing the signal used to terminate (if ---any) function default_dispatchers.on_exit(code, signal) local _ = log.info() and log.info('client_exit', { code = code, signal = signal }) @@ -233,7 +233,7 @@ end ---@private --- Default dispatcher for client errors. --- ----@param code (number): Error code +---@param code (integer): Error code ---@param err (any): Details about the error ---any) function default_dispatchers.on_error(code, err) @@ -270,7 +270,7 @@ local function create_read_loop(handle_body, on_no_chunk, on_error) end ---@class RpcClient ----@field message_index number +---@field message_index integer ---@field message_callbacks table ---@field notify_reply_callbacks table ---@field transport table @@ -588,7 +588,7 @@ end --- and port --- ---@param host string ----@param port number +---@param port integer ---@return function local function connect(host, port) return function(dispatchers) @@ -692,8 +692,8 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) ---@private --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. - ---@param code (number) Exit code - ---@param signal (number) Signal that was used to terminate (if any) + ---@param code (integer) Exit code + ---@param signal (integer) Signal that was used to terminate (if any) local function onexit(code, signal) stdin:close() stdout:close() diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 7983d066b8..9eaccd539f 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -4,36 +4,36 @@ local util = require('vim.lsp.util') local bit = require('bit') --- @class STTokenRange ---- @field line number line number 0-based ---- @field start_col number start column 0-based ---- @field end_col number end column 0-based +--- @field line integer line number 0-based +--- @field start_col integer start column 0-based +--- @field end_col integer end column 0-based --- @field type string token type as string --- @field modifiers table token modifiers as a set. E.g., { static = true, readonly = true } --- @field marked boolean whether this token has had extmarks applied --- --- @class STCurrentResult ---- @field version number document version associated with this result +--- @field version integer document version associated with this result --- @field result_id string resultId from the server; used with delta requests --- @field highlights STTokenRange[] cache of highlight ranges for this document version ---- @field tokens number[] raw token array as received by the server. used for calculating delta responses +--- @field tokens integer[] raw token array as received by the server. used for calculating delta responses --- @field namespace_cleared boolean whether the namespace was cleared for this result yet --- --- @class STActiveRequest ---- @field request_id number the LSP request ID of the most recent request sent to the server ---- @field version number the document version associated with the most recent request +--- @field request_id integer the LSP request ID of the most recent request sent to the server +--- @field version integer the document version associated with the most recent request --- --- @class STClientState ---- @field namespace number +--- @field namespace integer --- @field active_request STActiveRequest --- @field current_result STCurrentResult ---@class STHighlighter ----@field active table ----@field bufnr number ----@field augroup number augroup for buffer events ----@field debounce number milliseconds to debounce requests for new tokens +---@field active table +---@field bufnr integer +---@field augroup integer augroup for buffer events +---@field debounce integer milliseconds to debounce requests for new tokens ---@field timer table uv_timer for debouncing requests for new tokens ----@field client_state table +---@field client_state table local STHighlighter = { active = {} } --- Do a binary search of the tokens in the half-open range [lo, hi). @@ -141,7 +141,7 @@ end --- Construct a new STHighlighter for the buffer --- ---@private ----@param bufnr number +---@param bufnr integer function STHighlighter.new(bufnr) local self = setmetatable({}, { __index = STHighlighter }) @@ -470,7 +470,7 @@ end --- in case the server supports delta requests. --- ---@private ----@param client_id number +---@param client_id integer function STHighlighter:mark_dirty(client_id) local state = self.client_state[client_id] assert(state) @@ -529,10 +529,10 @@ local M = {} --- client.server_capabilities.semanticTokensProvider = nil --- --- ----@param bufnr number ----@param client_id number +---@param bufnr integer +---@param client_id integer ---@param opts (nil|table) Optional keyword arguments ---- - debounce (number, default: 200): Debounce token requests +--- - debounce (integer, default: 200): Debounce token requests --- to the server by the given number in milliseconds function M.start(bufnr, client_id, opts) vim.validate({ @@ -585,8 +585,8 @@ end --- of `start()`, so you should only need this function to manually disengage the semantic --- token engine without fully detaching the LSP client from the buffer. --- ----@param bufnr number ----@param client_id number +---@param bufnr integer +---@param client_id integer function M.stop(bufnr, client_id) vim.validate({ bufnr = { bufnr, 'n', false }, @@ -608,15 +608,15 @@ end --- Return the semantic token(s) at the given position. --- If called without arguments, returns the token under the cursor. --- ----@param bufnr number|nil Buffer number (0 for current buffer, default) ----@param row number|nil Position row (default cursor position) ----@param col number|nil Position column (default cursor position) +---@param bufnr integer|nil Buffer number (0 for current buffer, default) +---@param row integer|nil Position row (default cursor position) +---@param col integer|nil Position column (default cursor position) --- ---@return table|nil (table|nil) List of tokens at position. Each token has --- the following fields: ---- - line (number) line number, 0-based ---- - start_col (number) start column, 0-based ---- - end_col (number) end column, 0-based +--- - line (integer) line number, 0-based +--- - start_col (integer) start column, 0-based +--- - end_col (integer) end column, 0-based --- - type (string) token type as string, e.g. "variable" --- - modifiers (table) token modifiers as a set. E.g., { static = true, readonly = true } function M.get_at_pos(bufnr, row, col) @@ -661,7 +661,7 @@ end --- Only has an effect if the buffer is currently active for semantic token --- highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) --- ----@param bufnr (number|nil) filter by buffer. All buffers if nil, current +---@param bufnr (integer|nil) filter by buffer. All buffers if nil, current --- buffer if 0 function M.force_refresh(bufnr) vim.validate({ @@ -689,11 +689,11 @@ end --- use inside |LspTokenUpdate| callbacks. ---@param token (table) a semantic token, found as `args.data.token` in --- |LspTokenUpdate|. ----@param bufnr (number) the buffer to highlight ----@param client_id (number) The ID of the |vim.lsp.client| +---@param bufnr (integer) the buffer to highlight +---@param client_id (integer) The ID of the |vim.lsp.client| ---@param hl_group (string) Highlight group name ---@param opts (table|nil) Optional parameters. ---- - priority: (number|nil) Priority for the applied extmark. Defaults +--- - priority: (integer|nil) Priority for the applied extmark. Defaults --- to `vim.highlight.priorities.semantic_tokens + 3` function M.highlight_token(token, bufnr, client_id, hl_group, opts) local highlighter = STHighlighter.active[bufnr] diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index 826352f036..fb5b0b3194 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -388,9 +388,9 @@ end --- Returns the range table for the difference between prev and curr lines ---@param prev_lines table list of lines ---@param curr_lines table list of lines ----@param firstline number line to begin search for first difference ----@param lastline number line to begin search in old_lines for last difference ----@param new_lastline number line to begin search in new_lines for last difference +---@param firstline integer line to begin search for first difference +---@param lastline integer line to begin search in old_lines for last difference +---@param new_lastline integer line to begin search in new_lines for last difference ---@param offset_encoding string encoding requested by language server ---@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent function M.compute_diff( diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 554e26022c..c9613dc7a7 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -121,9 +121,9 @@ end --- Convert byte index to `encoding` index. --- Convenience wrapper around vim.str_utfindex ---@param line string line to be indexed ----@param index number|nil byte index (utf-8), or `nil` for length +---@param index integer|nil byte index (utf-8), or `nil` for length ---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ----@return number `encoding` index of `index` in `line` +---@return integer `encoding` index of `index` in `line` function M._str_utfindex_enc(line, index, encoding) if not encoding then encoding = 'utf-16' @@ -149,9 +149,9 @@ end --- Convenience wrapper around vim.str_byteindex ---Alternative to vim.str_byteindex that takes an encoding. ---@param line string line to be indexed ----@param index number UTF index +---@param index integer UTF index ---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ----@return number byte (utf-8) index of `encoding` index `index` in `line` +---@return integer byte (utf-8) index of `encoding` index `index` in `line` function M._str_byteindex_enc(line, index, encoding) if not encoding then encoding = 'utf-16' @@ -239,9 +239,9 @@ end --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- ----@param bufnr number bufnr to get the lines from ----@param rows number[] zero-indexed line numbers ----@return table a table mapping rows to lines +---@param bufnr integer bufnr to get the lines from +---@param rows integer[] zero-indexed line numbers +---@return table a table mapping rows to lines local function get_lines(bufnr, rows) rows = type(rows) == 'table' and rows or { rows } @@ -321,8 +321,8 @@ end --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- ----@param bufnr number ----@param row number zero-indexed line number +---@param bufnr integer +---@param row integer zero-indexed line number ---@return string the line at row in filename local function get_line(bufnr, row) return get_lines(bufnr, { row })[row] @@ -386,7 +386,7 @@ end --- Applies a list of text edits to a buffer. ---@param text_edits table list of `TextEdit` objects ----@param bufnr number Buffer id +---@param bufnr integer Buffer id ---@param offset_encoding string utf-8|utf-16|utf-32 ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit function M.apply_text_edits(text_edits, bufnr, offset_encoding) @@ -571,7 +571,7 @@ end --- document. --- ---@param text_document_edit table: a `TextDocumentEdit` object ----@param index number: Optional index of the edit, if from a list of edits (or nil, if not from a list) +---@param index integer: Optional index of the edit, if from a list of edits (or nil, if not from a list) ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit function M.apply_text_document_edit(text_document_edit, index, offset_encoding) local text_document = text_document_edit.textDocument @@ -1009,11 +1009,11 @@ end --- Creates a table with sensible default options for a floating window. The --- table can be passed to |nvim_open_win()|. --- ----@param width (number) window width (in character cells) ----@param height (number) window height (in character cells) +---@param width (integer) window width (in character cells) +---@param height (integer) window height (in character cells) ---@param opts (table, optional) ---- - offset_x (number) offset to add to `col` ---- - offset_y (number) offset to add to `row` +--- - offset_x (integer) offset to add to `col` +--- - offset_y (integer) offset to add to `row` --- - border (string or table) override `border` --- - focusable (string or table) override `focusable` --- - zindex (string or table) override `zindex`, defaults to 50 @@ -1429,7 +1429,7 @@ end ---@private --- Closes the preview window --- ----@param winnr number window id of preview window +---@param winnr integer window id of preview window ---@param bufnrs table|nil optional list of ignored buffers local function close_preview_window(winnr, bufnrs) vim.schedule(function() @@ -1448,7 +1448,7 @@ end --- Creates autocommands to close a preview window when events happen. --- ---@param events table list of events ----@param winnr number window id of preview window +---@param winnr integer window id of preview window ---@param bufnrs table list of buffers where the preview window will remain visible ---@see |autocmd-events| local function close_preview_autocmd(events, winnr, bufnrs) @@ -1556,14 +1556,14 @@ end ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ---@param opts table with optional fields (additional keys are passed on to |nvim_open_win()|) ---- - height: (number) height of floating window ---- - width: (number) width of floating window +--- - height: (integer) height of floating window +--- - width: (integer) width of floating window --- - wrap: (boolean, default true) wrap long lines ---- - wrap_at: (number) character to wrap at for computing height when wrap is enabled ---- - max_width: (number) maximal width of floating window ---- - max_height: (number) maximal height of floating window ---- - pad_top: (number) number of lines to pad contents at top ---- - pad_bottom: (number) number of lines to pad contents at bottom +--- - wrap_at: (integer) character to wrap at for computing height when wrap is enabled +--- - max_width: (integer) maximal width of floating window +--- - max_height: (integer) maximal height of floating window +--- - pad_top: (integer) number of lines to pad contents at top +--- - pad_bottom: (integer) number of lines to pad contents at bottom --- - focus_id: (string) if a popup with this id is opened, then focus it --- - close_events: (table) list of events that closes the floating window --- - focusable: (boolean, default true) Make float focusable @@ -1672,7 +1672,7 @@ do --[[ References ]] --- Removes document highlights from a buffer. --- - ---@param bufnr number Buffer id + ---@param bufnr integer Buffer id function M.buf_clear_references(bufnr) validate({ bufnr = { bufnr, 'n', true } }) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) @@ -1680,7 +1680,7 @@ do --[[ References ]] --- Shows a list of document highlights for a certain buffer. --- - ---@param bufnr number Buffer id + ---@param bufnr integer Buffer id ---@param references table List of `DocumentHighlight` objects to highlight ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32". ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent @@ -1893,7 +1893,7 @@ function M.try_trim_markdown_code_blocks(lines) end ---@private ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` local function make_position_param(window, offset_encoding) window = window or 0 @@ -1913,7 +1913,7 @@ end --- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position. --- ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ---@returns `TextDocumentPositionParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams @@ -1928,7 +1928,7 @@ function M.make_position_params(window, offset_encoding) end --- Utility function for getting the encoding of the first LSP client on the given buffer. ----@param bufnr (number) buffer handle or 0 for current, defaults to current +---@param bufnr (integer) buffer handle or 0 for current, defaults to current ---@returns (string) encoding first client if there is one, nil otherwise function M._get_offset_encoding(bufnr) validate({ @@ -1966,7 +1966,7 @@ end --- `textDocument/codeAction`, `textDocument/colorPresentation`, --- `textDocument/rangeFormatting`. --- ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window` ---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---`current_position`, end = `current_position` } } @@ -1983,11 +1983,11 @@ end --- Using the given range in the current buffer, creates an object that --- is similar to |vim.lsp.util.make_range_params()|. --- ----@param start_pos number[]|nil {row, col} mark-indexed position. +---@param start_pos integer[]|nil {row, col} mark-indexed position. --- Defaults to the start of the last visual selection. ----@param end_pos number[]|nil {row, col} mark-indexed position. +---@param end_pos integer[]|nil {row, col} mark-indexed position. --- Defaults to the end of the last visual selection. ----@param bufnr number|nil buffer handle or 0 for current, defaults to current +---@param bufnr integer|nil buffer handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` ---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---`start_position`, end = `end_position` } } @@ -2028,7 +2028,7 @@ end --- Creates a `TextDocumentIdentifier` object for the current buffer. --- ----@param bufnr number|nil: Buffer handle, defaults to current +---@param bufnr integer|nil: Buffer handle, defaults to current ---@returns `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params(bufnr) @@ -2049,8 +2049,8 @@ end --- Returns indentation size. --- ---@see 'shiftwidth' ----@param bufnr (number|nil): Buffer handle, defaults to current ----@returns (number) indentation size +---@param bufnr (integer|nil): Buffer handle, defaults to current +---@returns (integer) indentation size function M.get_effective_tabstop(bufnr) validate({ bufnr = { bufnr, 'n', true } }) local bo = bufnr and vim.bo[bufnr] or vim.bo @@ -2077,11 +2077,11 @@ end --- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. --- ----@param buf number buffer number (0 for current) +---@param buf integer buffer number (0 for current) ---@param row 0-indexed line ---@param col 0-indexed byte offset in line ---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of `buf` ----@returns (number, number) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} +---@returns (integer, integer) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} function M.character_offset(buf, row, col, offset_encoding) local line = get_line(buf, row) if offset_encoding == nil then -- cgit From 4385f8a7430f8181189f385a6cfb4e295d30b21e Mon Sep 17 00:00:00 2001 From: jdrouhard Date: Tue, 7 Mar 2023 10:35:12 -0600 Subject: fix(lsp): change LspTokenUpdate to use buffer instead of pattern (#22559) --- runtime/lua/vim/lsp/semantic_tokens.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 9eaccd539f..a5e007a011 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -435,7 +435,7 @@ function STHighlighter:on_win(topline, botline) token.marked = true api.nvim_exec_autocmds('LspTokenUpdate', { - pattern = vim.api.nvim_buf_get_name(self.bufnr), + buffer = self.bufnr, modeline = false, data = { token = token, -- cgit From 75537768ef0b8cc35ef9c6aa906237e449640b46 Mon Sep 17 00:00:00 2001 From: Null Chilly <56817415+nullchilly@users.noreply.github.com> Date: Fri, 10 Mar 2023 20:10:38 +0700 Subject: perf(lsp): better binary search mid calculation in semantic token (#22607) This commit replaces the usage of math.floor((lo + hi) / 2) with the faster and equivalent bit.rshift(lo + hi, 1) for calculating the midpoint in binary search. --- runtime/lua/vim/lsp/semantic_tokens.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index a5e007a011..03532c33b7 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -44,7 +44,7 @@ local STHighlighter = { active = {} } ---@private local function lower_bound(tokens, line, lo, hi) while lo < hi do - local mid = math.floor((lo + hi) / 2) + local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). if tokens[mid].line < line then lo = mid + 1 else @@ -62,7 +62,7 @@ end ---@private local function upper_bound(tokens, line, lo, hi) while lo < hi do - local mid = math.floor((lo + hi) / 2) + local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). if line < tokens[mid].line then hi = mid else -- cgit From 236c20795eb9f11e21e0719b735ea741711acc08 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sat, 11 Mar 2023 07:35:23 +0100 Subject: revert: "fix(lsp): use buffer scheme for files not stored on disk" (#22604) Although using `buffer://` for unsaved file buffers fixes issues with language servers like eclipse.jdt.ls or ansible-language-server, it breaks completion and signature help for clangd. A regression is worse than a fix for something else, so this reverts commit 896d672736b32a8f4a4fa51844b44f266dcdcc6c. The spec change is also still in dicussion, see https://github.com/microsoft/language-server-protocol/pull/1679#discussion_r1130704886 --- runtime/lua/vim/lsp/util.lua | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index c9613dc7a7..342fad33c2 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2032,12 +2032,7 @@ end ---@returns `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params(bufnr) - bufnr = bufnr or 0 - local uri = vim.uri_from_bufnr(bufnr) - if not uv.fs_stat(api.nvim_buf_get_name(bufnr)) then - uri = uri:gsub('^file://', 'buffer://') - end - return { uri = uri } + return { uri = vim.uri_from_bufnr(bufnr or 0) } end --- Create the workspace params @@ -2070,7 +2065,7 @@ function M.make_formatting_params(options) insertSpaces = vim.bo.expandtab, }) return { - textDocument = M.make_text_document_params(0), + textDocument = { uri = vim.uri_from_bufnr(0) }, options = options, } end -- cgit From 865d8d4720ca72de1c385773ca4c597f3642874c Mon Sep 17 00:00:00 2001 From: Raphael Date: Sat, 11 Mar 2023 21:49:53 +0800 Subject: refactor(lsp): remove _resolve_capabilities_compat (#22628) --- runtime/lua/vim/lsp/protocol.lua | 174 --------------------------------------- 1 file changed, 174 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 27dd68645a..1686e22c48 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -854,7 +854,6 @@ function protocol.make_client_capabilities() } end -local if_nil = vim.F.if_nil --- Creates a normalized object describing LSP server capabilities. ---@param server_capabilities table Table of capabilities supported by the server ---@return table Normalized table of capabilities @@ -892,178 +891,5 @@ function protocol.resolve_capabilities(server_capabilities) return server_capabilities end ----@private ---- Creates a normalized object describing LSP server capabilities. --- @deprecated access resolved_capabilities instead ----@param server_capabilities table Table of capabilities supported by the server ----@return table Normalized table of capabilities -function protocol._resolve_capabilities_compat(server_capabilities) - local general_properties = {} - local text_document_sync_properties - do - local TextDocumentSyncKind = protocol.TextDocumentSyncKind - local textDocumentSync = server_capabilities.textDocumentSync - if textDocumentSync == nil then - -- Defaults if omitted. - text_document_sync_properties = { - text_document_open_close = false, - text_document_did_change = TextDocumentSyncKind.None, - -- text_document_did_change = false; - text_document_will_save = false, - text_document_will_save_wait_until = false, - text_document_save = false, - text_document_save_include_text = false, - } - elseif type(textDocumentSync) == 'number' then - -- Backwards compatibility - if not TextDocumentSyncKind[textDocumentSync] then - return nil, 'Invalid server TextDocumentSyncKind for textDocumentSync' - end - text_document_sync_properties = { - text_document_open_close = true, - text_document_did_change = textDocumentSync, - text_document_will_save = false, - text_document_will_save_wait_until = false, - text_document_save = true, - text_document_save_include_text = false, - } - elseif type(textDocumentSync) == 'table' then - text_document_sync_properties = { - text_document_open_close = if_nil(textDocumentSync.openClose, false), - text_document_did_change = if_nil(textDocumentSync.change, TextDocumentSyncKind.None), - text_document_will_save = if_nil(textDocumentSync.willSave, true), - text_document_will_save_wait_until = if_nil(textDocumentSync.willSaveWaitUntil, true), - text_document_save = if_nil(textDocumentSync.save, false), - text_document_save_include_text = if_nil( - type(textDocumentSync.save) == 'table' and textDocumentSync.save.includeText, - false - ), - } - else - return nil, string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)) - end - end - general_properties.completion = server_capabilities.completionProvider ~= nil - general_properties.hover = server_capabilities.hoverProvider or false - general_properties.goto_definition = server_capabilities.definitionProvider or false - general_properties.find_references = server_capabilities.referencesProvider or false - general_properties.document_highlight = server_capabilities.documentHighlightProvider or false - general_properties.document_symbol = server_capabilities.documentSymbolProvider or false - general_properties.workspace_symbol = server_capabilities.workspaceSymbolProvider or false - general_properties.document_formatting = server_capabilities.documentFormattingProvider or false - general_properties.document_range_formatting = server_capabilities.documentRangeFormattingProvider - or false - general_properties.call_hierarchy = server_capabilities.callHierarchyProvider or false - general_properties.execute_command = server_capabilities.executeCommandProvider ~= nil - - if server_capabilities.renameProvider == nil then - general_properties.rename = false - elseif type(server_capabilities.renameProvider) == 'boolean' then - general_properties.rename = server_capabilities.renameProvider - else - general_properties.rename = true - end - - if server_capabilities.codeLensProvider == nil then - general_properties.code_lens = false - general_properties.code_lens_resolve = false - elseif type(server_capabilities.codeLensProvider) == 'table' then - general_properties.code_lens = true - general_properties.code_lens_resolve = server_capabilities.codeLensProvider.resolveProvider - or false - else - error('The server sent invalid codeLensProvider') - end - - if server_capabilities.codeActionProvider == nil then - general_properties.code_action = false - elseif - type(server_capabilities.codeActionProvider) == 'boolean' - or type(server_capabilities.codeActionProvider) == 'table' - then - general_properties.code_action = server_capabilities.codeActionProvider - else - error('The server sent invalid codeActionProvider') - end - - if server_capabilities.declarationProvider == nil then - general_properties.declaration = false - elseif type(server_capabilities.declarationProvider) == 'boolean' then - general_properties.declaration = server_capabilities.declarationProvider - elseif type(server_capabilities.declarationProvider) == 'table' then - general_properties.declaration = server_capabilities.declarationProvider - else - error('The server sent invalid declarationProvider') - end - - if server_capabilities.typeDefinitionProvider == nil then - general_properties.type_definition = false - elseif type(server_capabilities.typeDefinitionProvider) == 'boolean' then - general_properties.type_definition = server_capabilities.typeDefinitionProvider - elseif type(server_capabilities.typeDefinitionProvider) == 'table' then - general_properties.type_definition = server_capabilities.typeDefinitionProvider - else - error('The server sent invalid typeDefinitionProvider') - end - - if server_capabilities.implementationProvider == nil then - general_properties.implementation = false - elseif type(server_capabilities.implementationProvider) == 'boolean' then - general_properties.implementation = server_capabilities.implementationProvider - elseif type(server_capabilities.implementationProvider) == 'table' then - general_properties.implementation = server_capabilities.implementationProvider - else - error('The server sent invalid implementationProvider') - end - - local workspace = server_capabilities.workspace - local workspace_properties = {} - if workspace == nil or workspace.workspaceFolders == nil then - -- Defaults if omitted. - workspace_properties = { - workspace_folder_properties = { - supported = false, - changeNotifications = false, - }, - } - elseif type(workspace.workspaceFolders) == 'table' then - workspace_properties = { - workspace_folder_properties = { - supported = if_nil(workspace.workspaceFolders.supported, false), - changeNotifications = if_nil(workspace.workspaceFolders.changeNotifications, false), - }, - } - else - error('The server sent invalid workspace') - end - - local signature_help_properties - if server_capabilities.signatureHelpProvider == nil then - signature_help_properties = { - signature_help = false, - signature_help_trigger_characters = {}, - } - elseif type(server_capabilities.signatureHelpProvider) == 'table' then - signature_help_properties = { - signature_help = true, - -- The characters that trigger signature help automatically. - signature_help_trigger_characters = server_capabilities.signatureHelpProvider.triggerCharacters - or {}, - } - else - error('The server sent invalid signatureHelpProvider') - end - - local capabilities = vim.tbl_extend( - 'error', - text_document_sync_properties, - signature_help_properties, - workspace_properties, - general_properties - ) - - return capabilities -end - return protocol -- vim:sw=2 ts=2 et -- cgit From d15abd1be4ae85b10174e3ee139d3b7605e87577 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sun, 12 Mar 2023 09:45:28 +0100 Subject: fix(lsp): use line start/end for visual line selection (#22632) Fixes https://github.com/neovim/neovim/issues/22629 --- runtime/lua/vim/lsp/buf.lua | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 6ac885c78f..0e16e8f820 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -118,8 +118,10 @@ function M.completion(context) end ---@private +---@param bufnr integer +---@param mode "v"|"V" ---@return table {start={row, col}, end={row, col}} using (1, 0) indexing -local function range_from_selection() +local function range_from_selection(bufnr, mode) -- TODO: Use `vim.region()` instead https://github.com/neovim/neovim/pull/13896 -- [bufnum, lnum, col, off]; both row and column 1-indexed @@ -138,6 +140,11 @@ local function range_from_selection() start_row, end_row = end_row, start_row start_col, end_col = end_col, start_col end + if mode == 'V' then + start_col = 1 + local lines = api.nvim_buf_get_lines(bufnr, end_row - 1, end_row, true) + end_col = #lines[1] + end return { ['start'] = { start_row, start_col - 1 }, ['end'] = { end_row, end_col - 1 }, @@ -200,7 +207,7 @@ function M.format(options) local mode = api.nvim_get_mode().mode local range = options.range if not range and mode == 'v' or mode == 'V' then - range = range_from_selection() + range = range_from_selection(bufnr, mode) end local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' @@ -772,7 +779,7 @@ function M.code_action(options) local end_ = assert(options.range['end'], 'range must have a `end` property') params = util.make_given_range_params(start, end_) elseif mode == 'v' or mode == 'V' then - local range = range_from_selection() + local range = range_from_selection(0, mode) params = util.make_given_range_params(range.start, range['end']) else params = util.make_range_params() -- cgit From f01f18cdf4ffc3ce035db5fde2f45493eebb7fd9 Mon Sep 17 00:00:00 2001 From: Dan Strokirk Date: Mon, 13 Mar 2023 14:01:34 +0100 Subject: fix(lsp): remove_workspace_folders fails if client has no workspace_folders #22633 When a client has no workspace_folders, (e.g., copilot), `pairs` code would crash. --- runtime/lua/vim/lsp/buf.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 0e16e8f820..8bf3764f5e 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -530,7 +530,7 @@ function M.remove_workspace_folder(workspace_folder) { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } ) for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do - for idx, folder in pairs(client.workspace_folders) do + for idx, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) client.workspace_folders[idx] = nil -- cgit From 8dde7c907ca9ad365895bded2c2f59e08f65d3ed Mon Sep 17 00:00:00 2001 From: hrsh7th <629908+hrsh7th@users.noreply.github.com> Date: Tue, 14 Mar 2023 20:59:43 +0900 Subject: fix(lsp): vim.lsp.util.apply_text_edits cursor validation #22636 Problem Using wrong variable when checking the cursor position is valid or not in vim.lsp.util.apply_text_edits. Solution Use the correct variable. --- runtime/lua/vim/lsp/util.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 342fad33c2..82c9e3bc87 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -436,7 +436,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) -- Some LSP servers are depending on the VSCode behavior. -- The VSCode will re-locate the cursor position after applying TextEdit so we also do it. - local is_current_buf = api.nvim_get_current_buf() == bufnr + local is_current_buf = api.nvim_get_current_buf() == bufnr or bufnr == 0 local cursor = (function() if not is_current_buf then return { @@ -464,7 +464,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) start_col = get_line_byte_from_position(bufnr, text_edit.range.start, offset_encoding), end_row = text_edit.range['end'].line, end_col = get_line_byte_from_position(bufnr, text_edit.range['end'], offset_encoding), - text = split(text_edit.newText, '\n', true), + text = split(text_edit.newText, '\n', { plain = true }), } local max = api.nvim_buf_line_count(bufnr) @@ -522,7 +522,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) if is_cursor_fixed then local is_valid_cursor = true is_valid_cursor = is_valid_cursor and cursor.row < max - is_valid_cursor = is_valid_cursor and cursor.col <= #(get_line(bufnr, max - 1) or '') + is_valid_cursor = is_valid_cursor and cursor.col <= #(get_line(bufnr, cursor.row) or '') if is_valid_cursor then api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col }) end -- cgit From 4f7879dff0f0dc22ddf4cb2a2095b88605a3bab0 Mon Sep 17 00:00:00 2001 From: Ivan Date: Tue, 14 Mar 2023 13:08:37 +0100 Subject: fix(lsp): kill buffers after renaming a directory #22618 Problem: When LSP client renames a directory, opened buffers in the edfitor are not renamed or closed. Then `:wall` shows errors. https://github.com/neovim/neovim/blob/master/runtime/lua/vim/lsp/util.lua#L776 works correctly if you try to rename a single file, but doesn't delete old buffers with `old_fname` is a dir. Solution: Update the logic in runtime/lua/vim/lsp/util.lua:rename() Fixes #22617 --- runtime/lua/vim/lsp/util.lua | 48 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 10 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 82c9e3bc87..48faddfce1 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -743,6 +743,20 @@ local function bufwinid(bufnr) end end +--- Get list of buffers for a directory +---@private +local function get_dir_bufs(path) + path = path:gsub('([^%w])', '%%%1') + local buffers = {} + for _, v in ipairs(vim.api.nvim_list_bufs()) do + local bufname = vim.api.nvim_buf_get_name(v):gsub('buffer://', '') + if bufname:find(path) then + table.insert(buffers, v) + end + end + return buffers +end + --- Rename old_fname to new_fname --- ---@param opts (table) @@ -755,12 +769,22 @@ function M.rename(old_fname, new_fname, opts) vim.notify('Rename target already exists. Skipping rename.') return end - local oldbuf = vim.fn.bufadd(old_fname) - vim.fn.bufload(oldbuf) - -- The there may be pending changes in the buffer - if vim.fn.isdirectory(old_fname) == 0 then - api.nvim_buf_call(oldbuf, function() + local oldbufs = {} + local win = nil + + if vim.fn.isdirectory(old_fname) == 1 then + oldbufs = get_dir_bufs(old_fname) + else + local oldbuf = vim.fn.bufadd(old_fname) + table.insert(oldbufs, oldbuf) + win = bufwinid(oldbuf) + end + + for _, b in ipairs(oldbufs) do + vim.fn.bufload(b) + -- The there may be pending changes in the buffer + api.nvim_buf_call(b, function() vim.cmd('w!') end) end @@ -768,12 +792,16 @@ function M.rename(old_fname, new_fname, opts) local ok, err = os.rename(old_fname, new_fname) assert(ok, err) - local newbuf = vim.fn.bufadd(new_fname) - local win = bufwinid(oldbuf) - if win then - api.nvim_win_set_buf(win, newbuf) + if vim.fn.isdirectory(new_fname) == 0 then + local newbuf = vim.fn.bufadd(new_fname) + if win then + api.nvim_win_set_buf(win, newbuf) + end + end + + for _, b in ipairs(oldbufs) do + api.nvim_buf_delete(b, {}) end - api.nvim_buf_delete(oldbuf, { force = true }) end ---@private -- cgit From ea0b66d208dbcd5d5c0a17810596d769c7a0b6dd Mon Sep 17 00:00:00 2001 From: meredith Date: Thu, 23 Mar 2023 02:27:53 -0500 Subject: fix(lsp): Jump to tag locations reliably when :ltag is used (#22750) --- runtime/lua/vim/lsp/tagfunc.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index 49029f8599..eb25b67db9 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -9,7 +9,7 @@ local function mk_tag_item(name, range, uri, offset_encoding) return { name = name, filename = vim.uri_to_fname(uri), - cmd = string.format('call cursor(%d, %d)|', range.start.line + 1, byte), + cmd = string.format([[/\%%%dl\%%%dc/]], range.start.line + 1, byte), } end -- cgit From 36ee10057ab9a93144975449cc5e27f9b96e0af3 Mon Sep 17 00:00:00 2001 From: Micah Halter Date: Sat, 25 Mar 2023 09:01:39 -0400 Subject: fix(lsp): add missing silent check in lsp hover handler (#22763) Fixup to #21531. --- runtime/lua/vim/lsp/handlers.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index ee5b63d260..d01f8e6159 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -364,7 +364,9 @@ function M.hover(_, result, ctx, config) local markdown_lines = util.convert_input_to_markdown_lines(result.contents) markdown_lines = util.trim_empty_lines(markdown_lines) if vim.tbl_isempty(markdown_lines) then - vim.notify('No information available') + if config.silent ~= true then + vim.notify('No information available') + end return end return util.open_floating_preview(markdown_lines, 'markdown', config) -- cgit From 257d894d75bc583bb16f4dbe441907eb273d20ad Mon Sep 17 00:00:00 2001 From: Roberto Pommella Alegro Date: Sat, 25 Mar 2023 13:46:07 -0300 Subject: feat(lsp): render markdown in docs hover #22766 Problem: LSP docs hover (textDocument/hover) doesn't handle HTML escape seqs in markdown. Solution: Convert common HTML escape seqs to a nicer form, to display in the float. closees #22757 Signed-off-by: Kasama --- runtime/lua/vim/lsp/util.lua | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 48faddfce1..ebde7af16c 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1378,6 +1378,20 @@ function M.stylize_markdown(bufnr, contents, opts) end end + -- Handle some common html escape sequences + stripped = vim.tbl_map(function(line) + local escapes = { + ['>'] = '>', + ['<'] = '<', + ['"'] = '"', + ['''] = "'", + [' '] = ' ', + [' '] = ' ', + ['&'] = '&', + } + return (string.gsub(line, '&[^ ;]+;', escapes)) + end, stripped) + -- Compute size of float needed to show (wrapped) lines opts.wrap_at = opts.wrap_at or (vim.wo['wrap'] and api.nvim_win_get_width(0)) local width = M._make_floating_popup_size(stripped, opts) -- cgit From 226a6c3eaef2a7220841d3d5e69e1baf543b3d6f Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Thu, 30 Mar 2023 14:49:58 +0100 Subject: feat(diagnostic): add support for tags The LSP spec supports two tags that can be added to diagnostics: unnecessary and deprecated. Extend vim.diagnostic to be able to handle these. --- runtime/lua/vim/lsp/diagnostic.lua | 54 +++++++++++++++++++++++++++++--------- runtime/lua/vim/lsp/protocol.lua | 2 ++ runtime/lua/vim/lsp/types.lua | 17 ++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index b27bf6e425..dcc8f6549c 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -1,13 +1,6 @@ ---@brief lsp-diagnostic ---- ----@class Diagnostic ----@field range Range ----@field message string ----@field severity DiagnosticSeverity|nil ----@field code integer | string ----@field source string ----@field tags DiagnosticTag[] ----@field relatedInformation DiagnosticRelatedInformation[] + +local protocol = require('vim.lsp.protocol') local M = {} @@ -22,14 +15,16 @@ local function get_client_id(client_id) end ---@private +---@param severity lsp.DiagnosticSeverity local function severity_lsp_to_vim(severity) if type(severity) == 'string' then - severity = vim.lsp.protocol.DiagnosticSeverity[severity] + severity = protocol.DiagnosticSeverity[severity] end return severity end ---@private +---@return lsp.DiagnosticSeverity local function severity_vim_to_lsp(severity) if type(severity) == 'string' then severity = vim.diagnostic.severity[severity] @@ -38,6 +33,7 @@ local function severity_vim_to_lsp(severity) end ---@private +---@return integer local function line_byte_from_position(lines, lnum, col, offset_encoding) if not lines or offset_encoding == 'utf-8' then return col @@ -77,12 +73,41 @@ local function get_buf_lines(bufnr) return lines end +--- @private +--- @param diagnostic lsp.Diagnostic +--- @param client_id integer +--- @return table? +local function tags_lsp_to_vim(diagnostic, client_id) + local tags ---@type table? + for _, tag in ipairs(diagnostic.tags or {}) do + if tag == protocol.DiagnosticTag.Unnecessary then + tags = tags or {} + tags.unnecessary = true + elseif tag == protocol.DiagnosticTag.Deprecated then + tags = tags or {} + tags.deprecated = true + else + vim.notify_once( + string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id), + vim.log.levels.WARN + ) + end + end + return tags +end + ---@private +---@param diagnostics lsp.Diagnostic[] +---@param bufnr integer +---@param client_id integer +---@return Diagnostic[] local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) local buf_lines = get_buf_lines(bufnr) local client = vim.lsp.get_client_by_id(client_id) local offset_encoding = client and client.offset_encoding or 'utf-16' + ---@diagnostic disable-next-line:no-unknown return vim.tbl_map(function(diagnostic) + ---@cast diagnostic lsp.Diagnostic local start = diagnostic.range.start local _end = diagnostic.range['end'] return { @@ -94,12 +119,12 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) message = diagnostic.message, source = diagnostic.source, code = diagnostic.code, + tags = tags_lsp_to_vim(diagnostic, client_id), user_data = { lsp = { -- usage of user_data.lsp.code is deprecated in favor of the top-level code field code = diagnostic.code, codeDescription = diagnostic.codeDescription, - tags = diagnostic.tags, relatedInformation = diagnostic.relatedInformation, data = diagnostic.data, }, @@ -108,9 +133,13 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) end, diagnostics) end ----@private +--- @private +--- @param diagnostics Diagnostic[] +--- @return lsp.Diagnostic[] local function diagnostic_vim_to_lsp(diagnostics) + ---@diagnostic disable-next-line:no-unknown return vim.tbl_map(function(diagnostic) + ---@cast diagnostic Diagnostic return vim.tbl_extend('keep', { -- "keep" the below fields over any duplicate fields in diagnostic.user_data.lsp range = { @@ -131,6 +160,7 @@ local function diagnostic_vim_to_lsp(diagnostics) end, diagnostics) end +---@type table local _client_namespaces = {} --- Get the diagnostic namespace associated with an LSP client |vim.diagnostic|. diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 1686e22c48..f4489ad17d 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -21,6 +21,7 @@ end --]=] local constants = { + --- @enum lsp.DiagnosticSeverity DiagnosticSeverity = { -- Reports an error. Error = 1, @@ -32,6 +33,7 @@ local constants = { Hint = 4, }, + --- @enum lsp.DiagnosticTag DiagnosticTag = { -- Unused or unnecessary code Unnecessary = 1, diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index 1aea6841ee..779f313aa7 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -18,3 +18,20 @@ ---@class lsp.FileEvent ---@field uri string ---@field type lsp.FileChangeType + +---@class lsp.Position +---@field line integer +---@field character integer + +---@class lsp.Range +---@field start lsp.Position +---@field end lsp.Position + +---@class lsp.Diagnostic +---@field range lsp.Range +---@field message string +---@field severity? lsp.DiagnosticSeverity +---@field code integer | string +---@field source string +---@field tags? lsp.DiagnosticTag[] +---@field relatedInformation DiagnosticRelatedInformation[] -- cgit From ed10e4ef60c63d924b9969abdf77adaad506b676 Mon Sep 17 00:00:00 2001 From: Akin <22454918+akinsho@users.noreply.github.com> Date: Fri, 31 Mar 2023 11:23:19 +0100 Subject: fix(diagnostic): use correct field name for tags (#22835) LSP tags are added to the diagnostic as "tags" but referred to as "_tags" in the diagnostic underline handler --- runtime/lua/vim/lsp/diagnostic.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index dcc8f6549c..3efa5c51ff 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -119,7 +119,7 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) message = diagnostic.message, source = diagnostic.source, code = diagnostic.code, - tags = tags_lsp_to_vim(diagnostic, client_id), + _tags = tags_lsp_to_vim(diagnostic, client_id), user_data = { lsp = { -- usage of user_data.lsp.code is deprecated in favor of the top-level code field -- cgit From bfb28b62dab756ec76a73506c2070ddf491a0cdd Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Thu, 13 Apr 2023 15:29:13 -0600 Subject: refactor: remove modelines from Lua files Now that we have builtin EditorConfig support and a formatting check in CI, these are not necessary. --- runtime/lua/vim/lsp/buf.lua | 1 - runtime/lua/vim/lsp/handlers.lua | 1 - runtime/lua/vim/lsp/log.lua | 1 - runtime/lua/vim/lsp/protocol.lua | 1 - runtime/lua/vim/lsp/rpc.lua | 1 - runtime/lua/vim/lsp/util.lua | 1 - 6 files changed, 6 deletions(-) (limited to 'runtime/lua/vim/lsp') 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/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..dca258e4b9 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -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 -- cgit From 4d04feb6629cb049cb2a13ba35f0c8d3c6b67ff4 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Fri, 14 Apr 2023 10:39:57 +0200 Subject: feat(lua): vim.tbl_contains supports general tables and predicates (#23040) * feat(lua): vim.tbl_contains supports general tables and predicates Problem: `vim.tbl_contains` only works for list-like tables (integer keys without gaps) and primitive values (in particular, not for nested tables). Solution: Rename `vim.tbl_contains` to `vim.list_contains` and add new `vim.tbl_contains` that works for general tables and optionally allows `value` to be a predicate function that is checked for every key. --- runtime/lua/vim/lsp/_snippet.lua | 4 ++-- runtime/lua/vim/lsp/codelens.lua | 2 +- runtime/lua/vim/lsp/util.lua | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') 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/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/util.lua b/runtime/lua/vim/lsp/util.lua index dca258e4b9..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 -- cgit From c08b03076167837cff9eb66c19440d727e6dad31 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Sat, 15 Apr 2023 23:40:48 +0200 Subject: refactor: deprecate checkhealth functions The following functions are deprecated and will be removed in Nvim v0.11: - health#report_start() - health#report_info() - health#report_ok() - health#report_warn() - health#report_error() - vim.health.report_start() - vim.health.report_info() - vim.health.report_ok() - vim.health.report_warn() - vim.health.report_error() Users should instead use these: - vim.health.start() - vim.health.info() - vim.health.ok() - vim.health.warn() - vim.health.error() --- runtime/lua/vim/lsp/health.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 987707e661..6ca468393e 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -2,8 +2,8 @@ local M = {} --- Performs a healthcheck for LSP function M.check() - local report_info = vim.health.report_info - local report_warn = vim.health.report_warn + local report_info = vim.health.info + local report_warn = vim.health.warn local log = require('vim.lsp.log') local current_log_level = log.get_level() @@ -29,7 +29,7 @@ function M.check() report_fn(string.format('Log size: %d KB', log_size / 1000)) local clients = vim.lsp.get_active_clients() - vim.health.report_start('vim.lsp: Active Clients') + vim.health.start('vim.lsp: Active Clients') if next(clients) then for _, client in pairs(clients) do report_info( -- cgit From e9b85acfbb8d3b1dd6f92deb187800be757c6c68 Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Sat, 22 Apr 2023 02:37:38 -0500 Subject: feat(lsp): enable workspace/didChangeWatchedFiles by default (#23190) --- runtime/lua/vim/lsp/protocol.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 2cb8fc7955..a7919f12f5 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -837,7 +837,7 @@ function protocol.make_client_capabilities() refreshSupport = true, }, didChangeWatchedFiles = { - dynamicRegistration = false, + dynamicRegistration = true, relativePatternSupport = true, }, }, -- cgit From edf05b005f34f59dd40468c36cc139e217345a71 Mon Sep 17 00:00:00 2001 From: jdrouhard Date: Mon, 1 May 2023 00:15:32 -0500 Subject: perf(lsp): process semantic tokens response in a coroutine that yields every 5ms (#23375) --- runtime/lua/vim/lsp/semantic_tokens.lua | 45 +++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 8 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 03532c33b7..b6b09c58b1 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -1,7 +1,8 @@ local api = vim.api +local bit = require('bit') local handlers = require('vim.lsp.handlers') local util = require('vim.lsp.util') -local bit = require('bit') +local uv = vim.loop --- @class STTokenRange --- @field line integer line number 0-based @@ -94,15 +95,38 @@ end --- ---@private ---@return STTokenRange[] -local function tokens_to_ranges(data, bufnr, client) +local function tokens_to_ranges(data, bufnr, client, request) local legend = client.server_capabilities.semanticTokensProvider.legend local token_types = legend.tokenTypes local token_modifiers = legend.tokenModifiers local ranges = {} + local start = uv.hrtime() + local ms_to_ns = 1000 * 1000 + local yield_interval_ns = 5 * ms_to_ns + local co, is_main = coroutine.running() + local line local start_char = 0 for i = 1, #data, 5 do + -- if this function is called from the main coroutine, let it run to completion with no yield + if not is_main then + local elapsed_ns = uv.hrtime() - start + + if elapsed_ns > yield_interval_ns then + vim.schedule(function() + coroutine.resume(co, util.buf_versions[bufnr]) + end) + if request.version ~= coroutine.yield() then + -- request became stale since the last time the coroutine ran. + -- abandon it by yielding without a way to resume + coroutine.yield() + end + + start = uv.hrtime() + end + end + local delta_line = data[i] line = line and line + delta_line or delta_line local delta_start = data[i + 1] @@ -280,7 +304,7 @@ function STHighlighter:send_request() local c = vim.lsp.get_client_by_id(ctx.client_id) local highlighter = STHighlighter.active[ctx.bufnr] if not err and c and highlighter then - highlighter:process_response(response, c, version) + coroutine.wrap(STHighlighter.process_response)(highlighter, response, c, version) end end, self.bufnr) @@ -315,11 +339,9 @@ function STHighlighter:process_response(response, client, version) return end - -- reset active request - state.active_request = {} - -- skip nil responses if response == nil then + state.active_request = {} return end @@ -347,12 +369,19 @@ function STHighlighter:process_response(response, client, version) tokens = response.data end - -- Update the state with the new results + -- convert token list to highlight ranges + -- this could yield and run over multiple event loop iterations + local highlights = tokens_to_ranges(tokens, self.bufnr, client, state.active_request) + + -- reset active request + state.active_request = {} + + -- update the state with the new results local current_result = state.current_result current_result.version = version current_result.result_id = response.resultId current_result.tokens = tokens - current_result.highlights = tokens_to_ranges(tokens, self.bufnr, client) + current_result.highlights = highlights current_result.namespace_cleared = false -- redraw all windows displaying buffer -- cgit From 648f777931d49b8013146f69d7e2776f69c52900 Mon Sep 17 00:00:00 2001 From: jdrouhard Date: Fri, 5 May 2023 00:41:36 -0500 Subject: perf(lsp): load buffer contents once when processing semantic tokens responses (#23484) perf(lsp): load buffer contents once when processing semantic token responses Using _get_line_byte_from_position() for each token's boundaries was a pretty huge bottleneck, since that function would load individual buffer lines via nvim_buf_get_lines() (plus a lot of extra overhead). So each token caused two calls to nvim_buf_get_lines() (once for the start position, and once for the end position). For semantic tokens, we only attach to buffers that have already been loaded, so we can safely just get all the lines for the entire buffer at once, and lift the rest of the _get_line_byte_from_position() implementation directly while bypassing the part that loads the buffer line. While I was looking at get_lines (used by _get_line_byte_from_position), I noticed that we were checking for non-file URIs before we even looked to see if we already had the buffer loaded. Moving the buffer-loaded check to be the first thing done in get_lines() more than halved the average time spent transforming the token list into highlight ranges vs when it was still using _get_line_byte_from_position. I ended up improving that loop more by not using get_lines, but figured the performance improvement it provided was worth leaving in. --- runtime/lua/vim/lsp/semantic_tokens.lua | 17 ++++++++++++----- runtime/lua/vim/lsp/util.lua | 12 ++++++------ 2 files changed, 18 insertions(+), 11 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index b6b09c58b1..376cac19a7 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -99,6 +99,7 @@ local function tokens_to_ranges(data, bufnr, client, request) local legend = client.server_capabilities.semanticTokensProvider.legend local token_types = legend.tokenTypes local token_modifiers = legend.tokenModifiers + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) local ranges = {} local start = uv.hrtime() @@ -137,11 +138,17 @@ local function tokens_to_ranges(data, bufnr, client, request) local modifiers = modifiers_from_number(data[i + 4], token_modifiers) ---@private - local function _get_byte_pos(char_pos) - return util._get_line_byte_from_position(bufnr, { - line = line, - character = char_pos, - }, client.offset_encoding) + local function _get_byte_pos(col) + if col > 0 then + local buf_line = lines[line + 1] or '' + local ok, result + ok, result = pcall(util._str_byteindex_enc, buf_line, col, client.offset_encoding) + if ok then + return result + end + return math.min(#buf_line, col) + end + return col end local start_col = _get_byte_pos(start_char) diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 31af2afb0b..8274361f6d 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -253,12 +253,17 @@ local function get_lines(bufnr, rows) ---@private local function buf_lines() local lines = {} - for _, row in pairs(rows) do + for _, row in ipairs(rows) do lines[row] = (api.nvim_buf_get_lines(bufnr, row, row + 1, false) or { '' })[1] end return lines end + -- use loaded buffers if available + if vim.fn.bufloaded(bufnr) == 1 then + return buf_lines() + end + local uri = vim.uri_from_bufnr(bufnr) -- load the buffer if this is not a file uri @@ -268,11 +273,6 @@ local function get_lines(bufnr, rows) return buf_lines() end - -- use loaded buffers if available - if vim.fn.bufloaded(bufnr) == 1 then - return buf_lines() - end - local filename = api.nvim_buf_get_name(bufnr) -- get the data from the file -- cgit From 075a72d5ff9d49b1e93c0253b54931ecdcf673f3 Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Tue, 9 May 2023 11:12:54 -0500 Subject: fix(lsp): fix relative patterns for `workspace/didChangeWatchedFiles` (#23548) --- runtime/lua/vim/lsp/_watchfiles.lua | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 533a955925..3a78724d79 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -198,16 +198,17 @@ function M.register(reg, ctx) end local watch_regs = {} for _, w in ipairs(reg.registerOptions.watchers) do + local relative_pattern = false local glob_patterns = {} if type(w.globPattern) == 'string' then for _, folder in ipairs(client.workspace_folders) do table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) end else + relative_pattern = true table.insert(glob_patterns, w.globPattern) end for _, glob_pattern in ipairs(glob_patterns) do - local pattern = parse(glob_pattern.pattern) local base_dir = nil if type(glob_pattern.baseUri) == 'string' then base_dir = glob_pattern.baseUri @@ -216,9 +217,16 @@ function M.register(reg, ctx) end assert(base_dir, "couldn't identify root of watch") base_dir = vim.uri_to_fname(base_dir) + local kind = w.kind or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete + local pattern = glob_pattern.pattern + if relative_pattern then + pattern = base_dir .. '/' .. pattern + end + pattern = parse(pattern) + table.insert(watch_regs, { base_dir = base_dir, pattern = pattern, -- cgit From 512a90520e3287b9962ed7853d1f1021b564a133 Mon Sep 17 00:00:00 2001 From: Raphael Date: Sat, 13 May 2023 17:27:05 +0800 Subject: refactor(lsp): mark server_ready function as deprecated (#23520) --- runtime/lua/vim/lsp/buf.lua | 2 ++ 1 file changed, 2 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 3d9011656f..a307dea673 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -31,7 +31,9 @@ end --- ready. --- ---@returns `true` if server responds. +---@deprecated function M.server_ready() + vim.deprecate('vim.lsp.buf.server_ready', nil, '0.10.0') return not not vim.lsp.buf_notify(0, 'window/progress', {}) end -- cgit From 073035a030f5ef8ae9b9ca51552f887944c52eaa Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Sat, 20 May 2023 00:45:39 -0500 Subject: fix(lsp): don't register didChangeWatchedFiles when capability not set (#23689) Some LSP servers (tailwindcss, rome) are known to request registration for `workspace/didChangeWatchedFiles` even when the corresponding client capability does not advertise support. This change adds an extra check in the `client/registerCapability` handler not to start a watch unless the client capability is set appropriately. --- runtime/lua/vim/lsp/_watchfiles.lua | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 3a78724d79..cf2c57db1f 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -193,7 +193,12 @@ local to_lsp_change_type = { function M.register(reg, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) - if not client.workspace_folders then + if + -- Ill-behaved servers may not honor the client capability and try to register + -- anyway, so ignore requests when the user has opted out of the feature. + not client.config.capabilities.workspace.didChangeWatchedFiles.dynamicRegistration + or not client.workspace_folders + then return end local watch_regs = {} -- cgit From 1fe1bb084d0099fc4f9bfdc11189485d0f74b75a Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Mon, 19 Dec 2022 16:37:45 +0000 Subject: refactor(options): deprecate nvim[_buf|_win]_[gs]et_option Co-authored-by: zeertzjq Co-authored-by: famiu --- runtime/lua/vim/lsp/handlers.lua | 2 +- runtime/lua/vim/lsp/util.lua | 30 +++++++++++++----------------- 2 files changed, 14 insertions(+), 18 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 71bef43bc1..8e926c4644 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -454,7 +454,7 @@ function M.signature_help(_, result, ctx, config) local client = vim.lsp.get_client_by_id(ctx.client_id) local triggers = vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters') - local ft = api.nvim_buf_get_option(ctx.bufnr, 'filetype') + local ft = vim.bo[ctx.bufnr].filetype local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers) lines = util.trim_empty_lines(lines) if vim.tbl_isempty(lines) then diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 8274361f6d..9fffc845b1 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -401,7 +401,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) if not api.nvim_buf_is_loaded(bufnr) then vim.fn.bufload(bufnr) end - api.nvim_buf_set_option(bufnr, 'buflisted', true) + vim.bo[bufnr].buflisted = true -- Fix reversed range and indexing each text_edits local index = 0 @@ -530,11 +530,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) -- Remove final line if needed local fix_eol = has_eol_text_edit - fix_eol = fix_eol - and ( - api.nvim_buf_get_option(bufnr, 'eol') - or (api.nvim_buf_get_option(bufnr, 'fixeol') and not api.nvim_buf_get_option(bufnr, 'binary')) - ) + fix_eol = fix_eol and (vim.bo[bufnr].eol or (vim.bo[bufnr].fixeol and not vim.bo[bufnr].binary)) fix_eol = fix_eol and get_line(bufnr, max - 1) == '' if fix_eol then api.nvim_buf_set_lines(bufnr, -2, -1, false, {}) @@ -1076,7 +1072,7 @@ function M.make_floating_popup_options(width, height, opts) local wincol = opts.relative == 'mouse' and vim.fn.getmousepos().column or vim.fn.wincol() - if wincol + width + (opts.offset_x or 0) <= api.nvim_get_option('columns') then + if wincol + width + (opts.offset_x or 0) <= vim.o.columns then anchor = anchor .. 'W' col = 0 else @@ -1142,7 +1138,7 @@ function M.show_document(location, offset_encoding, opts) or focus and api.nvim_get_current_win() or create_window_without_focus() - api.nvim_buf_set_option(bufnr, 'buflisted', true) + vim.bo[bufnr].buflisted = true api.nvim_win_set_buf(win, bufnr) if focus then api.nvim_set_current_win(win) @@ -1201,12 +1197,12 @@ function M.preview_location(location, opts) end local range = location.targetRange or location.range local contents = api.nvim_buf_get_lines(bufnr, range.start.line, range['end'].line + 1, false) - local syntax = api.nvim_buf_get_option(bufnr, 'syntax') + local syntax = vim.bo[bufnr].syntax if syntax == '' then -- When no syntax is set, we use filetype as fallback. This might not result -- in a valid syntax definition. See also ft detection in stylize_markdown. -- An empty syntax is more common now with TreeSitter, since TS disables syntax. - syntax = api.nvim_buf_get_option(bufnr, 'filetype') + syntax = vim.bo[bufnr].filetype end opts = opts or {} opts.focus_id = 'location' @@ -1665,7 +1661,7 @@ function M.open_floating_preview(contents, syntax, opts) contents = M.stylize_markdown(floating_bufnr, contents, opts) else if syntax then - api.nvim_buf_set_option(floating_bufnr, 'syntax', syntax) + vim.bo[floating_bufnr].syntax = syntax end api.nvim_buf_set_lines(floating_bufnr, 0, -1, true, contents) end @@ -1681,16 +1677,16 @@ function M.open_floating_preview(contents, syntax, opts) local float_option = M.make_floating_popup_options(width, height, opts) local floating_winnr = api.nvim_open_win(floating_bufnr, false, float_option) if do_stylize then - api.nvim_win_set_option(floating_winnr, 'conceallevel', 2) - api.nvim_win_set_option(floating_winnr, 'concealcursor', 'n') + vim.wo[floating_winnr].conceallevel = 2 + vim.wo[floating_winnr].concealcursor = 'n' end -- disable folding - api.nvim_win_set_option(floating_winnr, 'foldenable', false) + vim.wo[floating_winnr].foldenable = false -- soft wrapping - api.nvim_win_set_option(floating_winnr, 'wrap', opts.wrap) + vim.wo[floating_winnr].wrap = opts.wrap - api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) - api.nvim_buf_set_option(floating_bufnr, 'bufhidden', 'wipe') + vim.bo[floating_bufnr].modifiable = false + vim.bo[floating_bufnr].bufhidden = 'wipe' api.nvim_buf_set_keymap( floating_bufnr, 'n', -- cgit From ddd92a70d2aab5247895e89abaaa79c62ba7dbb4 Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Sun, 28 May 2023 07:51:28 +0200 Subject: feat(lsp): initial support for dynamic capabilities (#23681) - `client.dynamic_capabilities` is an object that tracks client register/unregister - `client.supports_method` will additionally check if a dynamic capability supports the method, taking document filters into account. But only if the client enabled `dynamicRegistration` for the capability - updated the default client capabilities to include dynamicRegistration for: - formatting - rangeFormatting - hover - codeAction - hover - rename --- runtime/lua/vim/lsp/_dynamic.lua | 109 +++++++++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/buf.lua | 6 +-- runtime/lua/vim/lsp/handlers.lua | 28 +++++++--- runtime/lua/vim/lsp/protocol.lua | 13 +++-- runtime/lua/vim/lsp/types.lua | 28 ++++++++++ 5 files changed, 168 insertions(+), 16 deletions(-) create mode 100644 runtime/lua/vim/lsp/_dynamic.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_dynamic.lua b/runtime/lua/vim/lsp/_dynamic.lua new file mode 100644 index 0000000000..04040e8e28 --- /dev/null +++ b/runtime/lua/vim/lsp/_dynamic.lua @@ -0,0 +1,109 @@ +local wf = require('vim.lsp._watchfiles') + +--- @class lsp.DynamicCapabilities +--- @field capabilities table +--- @field client_id number +local M = {} + +--- @param client_id number +function M.new(client_id) + return setmetatable({ + capabilities = {}, + client_id = client_id, + }, { __index = M }) +end + +function M:supports_registration(method) + local client = vim.lsp.get_client_by_id(self.client_id) + if not client then + return false + end + local capability = vim.tbl_get(client.config.capabilities, unpack(vim.split(method, '/'))) + return type(capability) == 'table' and capability.dynamicRegistration +end + +--- @param registrations lsp.Registration[] +--- @private +function M:register(registrations) + -- remove duplicates + self:unregister(registrations) + for _, reg in ipairs(registrations) do + local method = reg.method + if not self.capabilities[method] then + self.capabilities[method] = {} + end + table.insert(self.capabilities[method], reg) + end +end + +--- @param unregisterations lsp.Unregistration[] +--- @private +function M:unregister(unregisterations) + for _, unreg in ipairs(unregisterations) do + local method = unreg.method + if not self.capabilities[method] then + return + end + local id = unreg.id + for i, reg in ipairs(self.capabilities[method]) do + if reg.id == id then + table.remove(self.capabilities[method], i) + break + end + end + end +end + +--- @param method string +--- @param opts? {bufnr?: number} +--- @return lsp.Registration? (table|nil) the registration if found +--- @private +function M:get(method, opts) + opts = opts or {} + opts.bufnr = opts.bufnr or vim.api.nvim_get_current_buf() + for _, reg in ipairs(self.capabilities[method] or {}) do + if not reg.registerOptions then + return reg + end + local documentSelector = reg.registerOptions.documentSelector + if not documentSelector then + return reg + end + if M.match(opts.bufnr, documentSelector) then + return reg + end + end +end + +--- @param method string +--- @param opts? {bufnr?: number} +--- @private +function M:supports(method, opts) + return self:get(method, opts) ~= nil +end + +--- @param bufnr number +--- @param documentSelector lsp.DocumentSelector +--- @private +function M.match(bufnr, documentSelector) + local ft = vim.bo[bufnr].filetype + local uri = vim.uri_from_bufnr(bufnr) + local fname = vim.uri_to_fname(uri) + for _, filter in ipairs(documentSelector) do + local matches = true + if filter.language and ft ~= filter.language then + matches = false + end + if matches and filter.scheme and not vim.startswith(uri, filter.scheme .. ':') then + matches = false + end + if matches and filter.pattern and not wf._match(filter.pattern, fname) then + matches = false + end + if matches then + return true + end + end +end + +return M diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index a307dea673..b2f202c4ba 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -683,11 +683,7 @@ local function on_code_action_results(results, ctx, options) -- local client = vim.lsp.get_client_by_id(action_tuple[1]) local action = action_tuple[2] - if - not action.edit - and client - and vim.tbl_get(client.server_capabilities, 'codeActionProvider', 'resolveProvider') - then + if not action.edit and client and client.supports_method('codeAction/resolve') then client.request('codeAction/resolve', action, function(err, resolved_action) if err then vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 8e926c4644..5346160871 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -118,22 +118,30 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability M['client/registerCapability'] = function(_, result, ctx) - local log_unsupported = false + local client_id = ctx.client_id + ---@type lsp.Client + local client = vim.lsp.get_client_by_id(client_id) + + client.dynamic_capabilities:register(result.registrations) + for bufnr, _ in ipairs(client.attached_buffers) do + vim.lsp._set_defaults(client, bufnr) + end + + ---@type string[] + local unsupported = {} for _, reg in ipairs(result.registrations) do if reg.method == 'workspace/didChangeWatchedFiles' then require('vim.lsp._watchfiles').register(reg, ctx) - else - log_unsupported = true + elseif not client.dynamic_capabilities:supports_registration(reg.method) then + unsupported[#unsupported + 1] = reg.method end end - if log_unsupported then - local client_id = ctx.client_id + if #unsupported > 0 then local warning_tpl = 'The language server %s triggers a registerCapability ' - .. 'handler despite dynamicRegistration set to false. ' + .. 'handler for %s despite dynamicRegistration set to false. ' .. 'Report upstream, this warning is harmless' - local client = vim.lsp.get_client_by_id(client_id) local client_name = client and client.name or string.format('id=%d', client_id) - local warning = string.format(warning_tpl, client_name) + local warning = string.format(warning_tpl, client_name, table.concat(unsupported, ', ')) log.warn(warning) end return vim.NIL @@ -141,6 +149,10 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability M['client/unregisterCapability'] = function(_, result, ctx) + local client_id = ctx.client_id + local client = vim.lsp.get_client_by_id(client_id) + client.dynamic_capabilities:unregister(result.unregisterations) + for _, unreg in ipairs(result.unregisterations) do if unreg.method == 'workspace/didChangeWatchedFiles' then require('vim.lsp._watchfiles').unregister(unreg, ctx) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index a7919f12f5..a28ff407b7 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -697,7 +697,7 @@ function protocol.make_client_capabilities() didSave = true, }, codeAction = { - dynamicRegistration = false, + dynamicRegistration = true, codeActionLiteralSupport = { codeActionKind = { @@ -714,6 +714,12 @@ function protocol.make_client_capabilities() properties = { 'edit' }, }, }, + formatting = { + dynamicRegistration = true, + }, + rangeFormatting = { + dynamicRegistration = true, + }, completion = { dynamicRegistration = false, completionItem = { @@ -747,6 +753,7 @@ function protocol.make_client_capabilities() }, definition = { linkSupport = true, + dynamicRegistration = true, }, implementation = { linkSupport = true, @@ -755,7 +762,7 @@ function protocol.make_client_capabilities() linkSupport = true, }, hover = { - dynamicRegistration = false, + dynamicRegistration = true, contentFormat = { protocol.MarkupKind.Markdown, protocol.MarkupKind.PlainText }, }, signatureHelp = { @@ -790,7 +797,7 @@ function protocol.make_client_capabilities() hierarchicalDocumentSymbolSupport = true, }, rename = { - dynamicRegistration = false, + dynamicRegistration = true, prepareSupport = true, }, publishDiagnostics = { diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index 779f313aa7..e77e1fb63a 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -35,3 +35,31 @@ ---@field source string ---@field tags? lsp.DiagnosticTag[] ---@field relatedInformation DiagnosticRelatedInformation[] + +--- @class lsp.DocumentFilter +--- @field language? string +--- @field scheme? string +--- @field pattern? string + +--- @alias lsp.DocumentSelector lsp.DocumentFilter[] + +--- @alias lsp.RegisterOptions any | lsp.StaticRegistrationOptions | lsp.TextDocumentRegistrationOptions + +--- @class lsp.Registration +--- @field id string +--- @field method string +--- @field registerOptions? lsp.RegisterOptions + +--- @alias lsp.RegistrationParams {registrations: lsp.Registration[]} + +--- @class lsp.StaticRegistrationOptions +--- @field id? string + +--- @class lsp.TextDocumentRegistrationOptions +--- @field documentSelector? lsp.DocumentSelector + +--- @class lsp.Unregistration +--- @field id string +--- @field method string + +--- @alias lsp.UnregistrationParams {unregisterations: lsp.Unregistration[]} -- cgit From dd3fa645735539c75b72dc1b0114278b5fa57f7f Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Tue, 30 May 2023 19:15:07 +0200 Subject: fix(lsp): fix dynamic registration of code actions (#23826) --- runtime/lua/vim/lsp/buf.lua | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index b2f202c4ba..bb3ca0e6d6 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -681,9 +681,16 @@ local function on_code_action_results(results, ctx, options) -- command: string -- arguments?: any[] -- + ---@type lsp.Client local client = vim.lsp.get_client_by_id(action_tuple[1]) local action = action_tuple[2] - if not action.edit and client and client.supports_method('codeAction/resolve') then + + local reg = client.dynamic_capabilities:get('textDocument/codeAction', { bufnr = ctx.bufnr }) + + local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') + or client.supports_method('codeAction/resolve') + + if not action.edit and client and supports_resolve then client.request('codeAction/resolve', action, function(err, resolved_action) if err then vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) -- cgit From 15641f38cf4b489a7c83e2c3aa6efc4c63009f00 Mon Sep 17 00:00:00 2001 From: Gregory Anders Date: Thu, 1 Jun 2023 11:39:51 -0500 Subject: feat(lsp): include positionEncodings in default client capabilities --- runtime/lua/vim/lsp/protocol.lua | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index a28ff407b7..7e49a572e7 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -634,6 +634,13 @@ export interface WorkspaceClientCapabilities { --- capabilities. function protocol.make_client_capabilities() return { + general = { + positionEncodings = { + 'utf-8', + 'utf-16', + 'utf-32', + }, + }, textDocument = { semanticTokens = { dynamicRegistration = false, -- cgit From 2db719f6c2b677fcbc197b02fe52764a851523b2 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Sat, 3 Jun 2023 11:06:00 +0100 Subject: feat(lua): rename vim.loop -> vim.uv (#22846) --- runtime/lua/vim/lsp/health.lua | 2 +- runtime/lua/vim/lsp/log.lua | 4 ++-- runtime/lua/vim/lsp/rpc.lua | 4 ++-- runtime/lua/vim/lsp/semantic_tokens.lua | 2 +- runtime/lua/vim/lsp/util.lua | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 6ca468393e..8817bb71de 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -22,7 +22,7 @@ function M.check() local log_path = vim.lsp.get_log_path() report_info(string.format('Log path: %s', log_path)) - local log_file = vim.loop.fs_stat(log_path) + local log_file = vim.uv.fs_stat(log_path) local log_size = log_file and log_file.size or 0 local report_fn = (log_size / 1000000 > 100 and report_warn or report_info) diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index 3d5bc06c3f..07d0500797 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -31,7 +31,7 @@ do end end - local path_sep = vim.loop.os_uname().version:match('Windows') and '\\' or '/' + local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/' ---@private local function path_join(...) return table.concat(vim.tbl_flatten({ ... }), path_sep) @@ -68,7 +68,7 @@ do return false end - local log_info = vim.loop.fs_stat(logfilename) + local log_info = vim.uv.fs_stat(logfilename) if log_info and log_info.size > 1e9 then local warn_msg = string.format( 'LSP client log is large (%d MB): %s', diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index af3190c9bd..5f48effebf 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -1,4 +1,4 @@ -local uv = vim.loop +local uv = vim.uv local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') local validate, schedule, schedule_wrap = vim.validate, vim.schedule, vim.schedule_wrap @@ -691,7 +691,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) }) ---@private - --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. + --- Callback for |vim.uv.spawn()| Closes all streams and runs the `on_exit` dispatcher. ---@param code (integer) Exit code ---@param signal (integer) Signal that was used to terminate (if any) local function onexit(code, signal) diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 376cac19a7..191cc7b400 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -2,7 +2,7 @@ local api = vim.api local bit = require('bit') local handlers = require('vim.lsp.handlers') local util = require('vim.lsp.util') -local uv = vim.loop +local uv = vim.uv --- @class STTokenRange --- @field line integer line number 0-based diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 9fffc845b1..53f8dba814 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -4,7 +4,7 @@ local validate = vim.validate local api = vim.api local list_extend = vim.list_extend local highlight = require('vim.highlight') -local uv = vim.loop +local uv = vim.uv local npcall = vim.F.npcall local split = vim.split -- cgit From 96e19533f60add50eea4598560bbd56de3b1fca3 Mon Sep 17 00:00:00 2001 From: Artyom Andreev Date: Sun, 4 Jun 2023 04:03:25 +0300 Subject: feat(lsp): set kind in select call for codelens #23889 --- runtime/lua/vim/lsp/codelens.lua | 1 + 1 file changed, 1 insertion(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 005a0047fa..ea8c52c334 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -97,6 +97,7 @@ function M.run() else vim.ui.select(options, { prompt = 'Code lenses:', + kind = 'codelens', format_item = function(option) return option.lens.command.title end, -- cgit From 5282d3299c9b1b07f3e02a9014bc2632cf3b4fed Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Mon, 5 Jun 2023 01:45:01 +0200 Subject: fix(lsp): restore marks after apply_text_edits() #14630 PROBLEM: Whenever any text edits are applied to the buffer, the `marks` part of those lines will be lost. This is mostly problematic for code formatters that format the whole buffer like `prettier`, `luafmt`, ... When doing atomic changes inside a vim doc, vim keeps track of those changes and can update the positions of marks accordingly, but in this case we have a whole doc that changed. There's no simple way to update the positions of all marks from the previous document state to the new document state. SOLUTION: * save marks right before `nvim_buf_set_lines` is called inside `apply_text_edits` * check if any marks were lost after doing `nvim_buf_set_lines` * restore those marks to the previous positions TEST CASE: * have a formatter enabled * open any file * create a couple of marks * indent the whole file to the right * save the file Before this change: all marks will be removed. After this change: they will be preserved. Fixes #14307 --- runtime/lua/vim/lsp/util.lua | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 53f8dba814..ba8c72128e 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -451,6 +451,14 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) } end)() + -- save and restore local marks since they get deleted by nvim_buf_set_lines + local marks = {} + for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do + if m.mark:match("^'[a-z]$") then + marks[m.mark:sub(2, 2)] = { m.pos[2], m.pos[3] - 1 } -- api-indexed + end + end + -- Apply text edits. local is_cursor_fixed = false local has_eol_text_edit = false @@ -518,6 +526,20 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) local max = api.nvim_buf_line_count(bufnr) + -- no need to restore marks that still exist + for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do + marks[m.mark:sub(2, 2)] = nil + end + -- restore marks + for mark, pos in pairs(marks) do + if pos then + -- make sure we don't go out of bounds + pos[1] = math.min(pos[1], max) + pos[2] = math.min(pos[2], #(get_line(bufnr, pos[1] - 1) or '')) + vim.api.nvim_buf_set_mark(bufnr or 0, mark, pos[1], pos[2], {}) + end + end + -- Apply fixed cursor position. if is_cursor_fixed then local is_valid_cursor = true -- cgit From 3c6d971e5488dc75b7db07c14d01f87827f28a67 Mon Sep 17 00:00:00 2001 From: Raphael Date: Mon, 5 Jun 2023 13:17:38 +0800 Subject: fix(lsp): set extra info only when it has a value (#23868) --- runtime/lua/vim/lsp/util.lua | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index ba8c72128e..e36014d07d 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -716,15 +716,18 @@ function M.text_document_completion_list_to_complete_items(result, prefix) local matches = {} for _, completion_item in ipairs(items) do - local info = ' ' + local info = '' local documentation = completion_item.documentation if documentation then if type(documentation) == 'string' and documentation ~= '' then info = documentation elseif type(documentation) == 'table' and type(documentation.value) == 'string' then info = documentation.value - -- else - -- TODO(ashkan) Validation handling here? + else + vim.notify( + ('invalid documentation value %s'):format(vim.inspect(documentation)), + vim.log.levels.WARN + ) end end @@ -734,7 +737,7 @@ function M.text_document_completion_list_to_complete_items(result, prefix) abbr = completion_item.label, kind = M._get_completion_item_kind_name(completion_item.kind), menu = completion_item.detail or '', - info = info, + info = #info > 0 and info or nil, icase = 1, dup = 1, empty = 1, -- cgit From 416fe8d185dcc072df7942953d867d9c605e9ffd Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Mon, 5 Jun 2023 00:19:31 -0500 Subject: refactor(lsp): use LPeg for watchfiles matching (#23788) --- runtime/lua/vim/lsp/_watchfiles.lua | 191 +++++++++++------------------------- 1 file changed, 56 insertions(+), 135 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index cf2c57db1f..14e5dc6cf8 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -1,152 +1,81 @@ local bit = require('bit') +local lpeg = require('lpeg') local watch = require('vim._watch') local protocol = require('vim.lsp.protocol') local M = {} ---@private ----Parses the raw pattern into a number of Lua-native patterns. +--- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" +--- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. --- ---@param pattern string The raw glob pattern ----@return table A list of Lua patterns. A match with any of them matches the input glob pattern. +---@return userdata An |lpeg| representation of the pattern, or nil if the pattern is invalid. local function parse(pattern) - local patterns = { '' } + local l = lpeg - local path_sep = '[/\\]' - local non_path_sep = '[^/\\]' + local P, S, V = lpeg.P, lpeg.S, lpeg.V + local C, Cc, Ct, Cf = lpeg.C, lpeg.Cc, lpeg.Ct, lpeg.Cf - local function append(chunks) - local new_patterns = {} - for _, p in ipairs(patterns) do - for _, chunk in ipairs(chunks) do - table.insert(new_patterns, p .. chunk) - end - end - patterns = new_patterns - end + local pathsep = '/' - local function split(s, sep) - local segments = {} - local segment = '' - local in_braces = false - local in_brackets = false - for i = 1, #s do - local c = string.sub(s, i, i) - if c == sep and not in_braces and not in_brackets then - table.insert(segments, segment) - segment = '' - else - if c == '{' then - in_braces = true - elseif c == '}' then - in_braces = false - elseif c == '[' then - in_brackets = true - elseif c == ']' then - in_brackets = false - end - segment = segment .. c - end + local function class(inv, ranges) + for i, r in ipairs(ranges) do + ranges[i] = r[1] .. r[2] end - if segment ~= '' then - table.insert(segments, segment) + local patt = l.R(unpack(ranges)) + if inv == '!' then + patt = P(1) - patt end - return segments + return patt end - local function escape(c) - if - c == '?' - or c == '.' - or c == '(' - or c == ')' - or c == '%' - or c == '[' - or c == ']' - or c == '*' - or c == '+' - or c == '-' - then - return '%' .. c - end - return c + local function add(acc, a) + return acc + a end - local segments = split(pattern, '/') - for i, segment in ipairs(segments) do - local last_seg = i == #segments - if segment == '**' then - local chunks = { - path_sep .. '-', - '.-' .. path_sep, - } - if last_seg then - chunks = { '.-' } - end - append(chunks) - else - local in_braces = false - local brace_val = '' - local in_brackets = false - local bracket_val = '' - for j = 1, #segment do - local char = string.sub(segment, j, j) - if char ~= '}' and in_braces then - brace_val = brace_val .. char - else - if in_brackets and (char ~= ']' or bracket_val == '') then - local res - if char == '-' then - res = char - elseif bracket_val == '' and char == '!' then - res = '^' - elseif char == '/' then - res = '' - else - res = escape(char) - end - bracket_val = bracket_val .. res - else - if char == '{' then - in_braces = true - elseif char == '[' then - in_brackets = true - elseif char == '}' then - local choices = split(brace_val, ',') - local parsed_choices = {} - for _, choice in ipairs(choices) do - table.insert(parsed_choices, parse(choice)) - end - append(vim.tbl_flatten(parsed_choices)) - in_braces = false - brace_val = '' - elseif char == ']' then - append({ '[' .. bracket_val .. ']' }) - in_brackets = false - bracket_val = '' - elseif char == '?' then - append({ non_path_sep }) - elseif char == '*' then - append({ non_path_sep .. '-' }) - else - append({ escape(char) }) - end - end - end - end + local function mul(acc, m) + return acc * m + end - if not last_seg and (segments[i + 1] ~= '**' or i + 1 < #segments) then - append({ path_sep }) - end - end + local function star(stars, after) + return (-after * (l.P(1) - pathsep)) ^ #stars * after end - return patterns + local function dstar(after) + return (-after * l.P(1)) ^ 0 * after + end + + local p = P({ + 'Pattern', + Pattern = V('Elem') ^ -1 * V('End'), + Elem = Cf( + (V('DStar') + V('Star') + V('Ques') + V('Class') + V('CondList') + V('Literal')) + * (V('Elem') + V('End')), + mul + ), + DStar = P('**') * (P(pathsep) * (V('Elem') + V('End')) + V('End')) / dstar, + Star = C(P('*') ^ 1) * (V('Elem') + V('End')) / star, + Ques = P('?') * Cc(l.P(1) - pathsep), + Class = P('[') * C(P('!') ^ -1) * Ct(Ct(C(1) * '-' * C(P(1) - ']')) ^ 1 * ']') / class, + CondList = P('{') * Cf(V('Cond') * (P(',') * V('Cond')) ^ 0, add) * '}', + -- TODO: '*' inside a {} condition is interpreted literally but should probably have the same + -- wildcard semantics it usually has. + -- Fixing this is non-trivial because '*' should match non-greedily up to "the rest of the + -- pattern" which in all other cases is the entire succeeding part of the pattern, but at the end of a {} + -- condition means "everything after the {}" where several other options separated by ',' may + -- exist in between that should not be matched by '*'. + Cond = Cf((V('Ques') + V('Class') + V('CondList') + (V('Literal') - S(',}'))) ^ 1, mul) + + Cc(l.P(0)), + Literal = P(1) / l.P, + End = P(-1) * Cc(l.P(-1)), + }) + + return p:match(pattern) end ---@private --- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern ---- Modeled after VSCode's implementation: https://github.com/microsoft/vscode/blob/0319eed971719ad48e9093daba9d65a5013ec5ab/src/vs/base/common/glob.ts#L509 --- ---@param pattern string|table The glob pattern (raw or parsed) to match. ---@param s string The string to match against pattern. @@ -155,15 +84,7 @@ function M._match(pattern, s) if type(pattern) == 'string' then pattern = parse(pattern) end - -- Since Lua's built-in string pattern matching does not have an alternate - -- operator like '|', `parse` will construct one pattern for each possible - -- alternative. Any pattern that matches thus matches the glob. - for _, p in ipairs(pattern) do - if s:match('^' .. p .. '$') then - return true - end - end - return false + return pattern:match(s) ~= nil end M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll @@ -226,11 +147,11 @@ function M.register(reg, ctx) local kind = w.kind or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete - local pattern = glob_pattern.pattern + local pattern = parse(glob_pattern.pattern) + assert(pattern, 'invalid pattern: ' .. glob_pattern.pattern) if relative_pattern then - pattern = base_dir .. '/' .. pattern + pattern = lpeg.P(base_dir .. '/') * pattern end - pattern = parse(pattern) table.insert(watch_regs, { base_dir = base_dir, -- cgit From ca26ec34386dfe98b0edf3de9aeb7b66f40d5efd Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Mon, 5 Jun 2023 08:21:23 -0500 Subject: fix(lsp): use only utf-16 in default client positionEncodings (#23903) The Nvim client does not yet support multiple offset encodings for clients in the same buffer. Until it does, stick to utf-16 by default. --- runtime/lua/vim/lsp/protocol.lua | 2 -- 1 file changed, 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 7e49a572e7..7558b5c6ba 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -636,9 +636,7 @@ function protocol.make_client_capabilities() return { general = { positionEncodings = { - 'utf-8', 'utf-16', - 'utf-32', }, }, textDocument = { -- cgit From 5f4895200a49d92e636dea9c5474ab5b0882384d Mon Sep 17 00:00:00 2001 From: max397574 <81827001+max397574@users.noreply.github.com> Date: Wed, 7 Jun 2023 13:32:39 +0200 Subject: feat(scripts): add lsp_types.lua (#23750) --- runtime/lua/vim/lsp/types/protocol.lua | 4398 ++++++++++++++++++++++++++++++++ 1 file changed, 4398 insertions(+) create mode 100644 runtime/lua/vim/lsp/types/protocol.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/types/protocol.lua b/runtime/lua/vim/lsp/types/protocol.lua new file mode 100644 index 0000000000..4b6660eb51 --- /dev/null +++ b/runtime/lua/vim/lsp/types/protocol.lua @@ -0,0 +1,4398 @@ +--[[ +This file is autogenerated from scripts/lsp_types.lua +Regenerate: +nvim -l scripts/lsp_types.lua gen --runtime/lua/vim/lsp/types/protocol.lua +--]] + +---@alias lsp.null nil +---@alias uinteger integer +---@alias lsp.decimal number +---@alias lsp.DocumentUri string +---@alias lsp.URI string +---@alias lsp.LSPObject table +---@alias lsp.LSPArray lsp.LSPAny[] +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|number|boolean|nil + +---@class lsp.ImplementationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Represents a location inside a resource, such as a line +---inside a text file. +---@class lsp.Location +---@field uri lsp.DocumentUri +---@field range lsp.Range + +---@class lsp.ImplementationRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.TypeDefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.TypeDefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---A workspace folder inside a client. +---@class lsp.WorkspaceFolder +---The associated URI for this workspace folder. +---@field uri lsp.URI +---The name of the workspace folder. Used to refer to this +---workspace folder in the user interface. +---@field name string + +---The parameters of a `workspace/didChangeWorkspaceFolders` notification. +---@class lsp.DidChangeWorkspaceFoldersParams +---The actual workspace folder change event. +---@field event lsp.WorkspaceFoldersChangeEvent + +---The parameters of a configuration request. +---@class lsp.ConfigurationParams +---@field items lsp.ConfigurationItem[] + +---Parameters for a {@link DocumentColorRequest}. +---@class lsp.DocumentColorParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a color range from a document. +---@class lsp.ColorInformation +---The range in the document where this color appears. +---@field range lsp.Range +---The actual color value for this color range. +---@field color lsp.Color + +---@class lsp.DocumentColorRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters for a {@link ColorPresentationRequest}. +---@class lsp.ColorPresentationParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The color to request presentations for. +---@field color lsp.Color +---The range where the color would be inserted. Serves as a context. +---@field range lsp.Range + +---@class lsp.ColorPresentation +---The label of this color presentation. It will be shown on the color +---picker header. By default this is also the text that is inserted when selecting +---this color presentation. +---@field label string +---An {@link TextEdit edit} which is applied to a document when selecting +---this presentation for the color. When `falsy` the {@link ColorPresentation.label label} +---is used. +---@field textEdit? lsp.TextEdit +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves. +---@field additionalTextEdits? lsp.TextEdit[] + +---@class lsp.WorkDoneProgressOptions +---@field workDoneProgress? boolean + +---General text document registration options. +---@class lsp.TextDocumentRegistrationOptions +---A document selector to identify the scope of the registration. If set to null +---the document selector provided on the client side will be used. +---@field documentSelector lsp.DocumentSelector|lsp.null + +---Parameters for a {@link FoldingRangeRequest}. +---@class lsp.FoldingRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a folding range. To be valid, start and end line must be bigger than zero and smaller +---than the number of lines in the document. Clients are free to ignore invalid ranges. +---@class lsp.FoldingRange +---The zero-based start line of the range to fold. The folded area starts after the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field startLine uinteger +---The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. +---@field startCharacter? uinteger +---The zero-based end line of the range to fold. The folded area ends with the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field endLine uinteger +---The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. +---@field endCharacter? uinteger +---Describes the kind of the folding range such as `comment' or 'region'. The kind +---is used to categorize folding ranges and used by commands like 'Fold all comments'. +---See {@link FoldingRangeKind} for an enumeration of standardized kinds. +---@field kind? lsp.FoldingRangeKind +---The text that the client should show when the specified range is +---collapsed. If not defined or not supported by the client, a default +---will be chosen by the client. +--- +---@since 3.17.0 +---@field collapsedText? string + +---@class lsp.FoldingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.DeclarationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.DeclarationRegistrationOptions: lsp.DeclarationOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in selection range requests. +---@class lsp.SelectionRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The positions inside the text document. +---@field positions lsp.Position[] + +---A selection range represents a part of a selection hierarchy. A selection range +---may have a parent selection range that contains it. +---@class lsp.SelectionRange +---The {@link Range range} of this selection range. +---@field range lsp.Range +---The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. +---@field parent? lsp.SelectionRange + +---@class lsp.SelectionRangeRegistrationOptions: lsp.SelectionRangeOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkDoneProgressCreateParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---@class lsp.WorkDoneProgressCancelParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---The parameter of a `textDocument/prepareCallHierarchy` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---Represents programming constructs like functions or constructors in the context +---of call hierarchy. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. +---Must be contained by the {@link CallHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a call hierarchy prepare and +---incoming calls or outgoing calls requests. +---@field data? lsp.LSPAny + +---Call hierarchy options used during static or dynamic registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `callHierarchy/incomingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an incoming call, e.g. a caller of a method or constructor. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCall +---The item that makes the call. +---@field from lsp.CallHierarchyItem +---The ranges at which the calls appear. This is relative to the caller +---denoted by {@link CallHierarchyIncomingCall.from `this.from`}. +---@field fromRanges lsp.Range[] + +---The parameter of a `callHierarchy/outgoingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCall +---The item that is called. +---@field to lsp.CallHierarchyItem +---The range at which this item is called. This is the range relative to the caller, e.g the item +---passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} +---and not {@link CallHierarchyOutgoingCall.to `this.to`}. +---@field fromRanges lsp.Range[] + +---@since 3.16.0 +---@class lsp.SemanticTokensParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---@since 3.16.0 +---@class lsp.SemanticTokens +---An optional result id. If provided and clients support delta updating +---the client will include the result id in the next semantic token request. +---A server can then instead of computing all semantic tokens again simply +---send a delta. +---@field resultId? string +---The actual tokens. +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensPartialResult +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The result id of a previous response. The result Id can either point to a full response +---or a delta response depending on what was received last. +---@field previousResultId string + +---@since 3.16.0 +---@class lsp.SemanticTokensDelta +---@field resultId? string +---The semantic token edits to transform a previous result into a new result. +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaPartialResult +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The range the semantic tokens are requested for. +---@field range lsp.Range + +---Params to show a resource in the UI. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentParams +---The uri to show. +---@field uri lsp.URI +---Indicates to show the resource in an external program. +---To show, for example, `https://code.visualstudio.com/` +---in the default WEB browser set `external` to `true`. +---@field external? boolean +---An optional property to indicate whether the editor +---showing the document should take focus or not. +---Clients might ignore this property if an external +---program is started. +---@field takeFocus? boolean +---An optional selection range if the document is a text +---document. Clients might ignore the property if an +---external program is started or the file is not a text +---file. +---@field selection? lsp.Range + +---The result of a showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentResult +---A boolean indicating if the show was successful. +---@field success boolean + +---@class lsp.LinkedEditingRangeParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRanges +---A list of ranges that can be edited together. The ranges must have +---identical length and contain identical text content. The ranges cannot overlap. +---@field ranges lsp.Range[] +---An optional word pattern (regular expression) that describes valid contents for +---the given ranges. If no pattern is provided, the client configuration's word +---pattern will be used. +---@field wordPattern? string + +---@class lsp.LinkedEditingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameters sent in notifications/requests for user-initiated creation of +---files. +--- +---@since 3.16.0 +---@class lsp.CreateFilesParams +---An array of all files/folders created in this operation. +---@field files lsp.FileCreate[] + +---A workspace edit represents changes to many resources managed in the workspace. The edit +---should either provide `changes` or `documentChanges`. If documentChanges are present +---they are preferred over `changes` if the client can handle versioned document edits. +--- +---Since version 3.13.0 a workspace edit can contain resource operations as well. If resource +---operations are present clients need to execute the operations in the order in which they +---are provided. So a workspace edit for example can consist of the following two changes: +---(1) a create file a.txt and (2) a text document edit which insert text into file a.txt. +--- +---An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will +---cause failure of the operation. How the client recovers from the failure is described by +---the client capability: `workspace.workspaceEdit.failureHandling` +---@class lsp.WorkspaceEdit +---Holds changes to existing resources. +---@field changes? table +---Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes +---are either an array of `TextDocumentEdit`s to express changes to n different text documents +---where each text document edit addresses a specific version of a text document. Or it can contain +---above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. +--- +---Whether a client supports versioned document edits is expressed via +---`workspace.workspaceEdit.documentChanges` client capability. +--- +---If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then +---only plain `TextEdit`s using the `changes` property are supported. +---@field documentChanges? lsp.TextDocumentEdit|lsp.CreateFile|lsp.RenameFile|lsp.DeleteFile[] +---A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and +---delete file / folder operations. +--- +---Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. +--- +---@since 3.16.0 +---@field changeAnnotations? table + +---The options to register for file operations. +--- +---@since 3.16.0 +---@class lsp.FileOperationRegistrationOptions +---The actual filters. +---@field filters lsp.FileOperationFilter[] + +---The parameters sent in notifications/requests for user-initiated renames of +---files. +--- +---@since 3.16.0 +---@class lsp.RenameFilesParams +---An array of all files/folders renamed in this operation. When a folder is renamed, only +---the folder will be included, and not its children. +---@field files lsp.FileRename[] + +---The parameters sent in notifications/requests for user-initiated deletes of +---files. +--- +---@since 3.16.0 +---@class lsp.DeleteFilesParams +---An array of all files/folders deleted in this operation. +---@field files lsp.FileDelete[] + +---@class lsp.MonikerParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Moniker definition to match LSIF 0.5 moniker definition. +--- +---@since 3.16.0 +---@class lsp.Moniker +---The scheme of the moniker. For example tsc or .Net +---@field scheme string +---The identifier of the moniker. The value is opaque in LSIF however +---schema owners are allowed to define the structure if they want. +---@field identifier string +---The scope in which the moniker is unique +---@field unique lsp.UniquenessLevel +---The moniker kind if known. +---@field kind? lsp.MonikerKind + +---@class lsp.MonikerRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameter of a `textDocument/prepareTypeHierarchy` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---@since 3.17.0 +---@class lsp.TypeHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace +---but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being +---picked, e.g. the name of a function. Must be contained by the +---{@link TypeHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a type hierarchy prepare and +---supertypes or subtypes requests. It could also be used to identify the +---type hierarchy in the server, helping improve the performance on +---resolving supertypes and subtypes. +---@field data? lsp.LSPAny + +---Type hierarchy options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `typeHierarchy/supertypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySupertypesParams +---@field item lsp.TypeHierarchyItem + +---The parameter of a `typeHierarchy/subtypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySubtypesParams +---@field item lsp.TypeHierarchyItem + +---A parameter literal used in inline value requests. +--- +---@since 3.17.0 +---@class lsp.InlineValueParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inline values should be computed. +---@field range lsp.Range +---Additional information about the context in which inline values were +---requested. +---@field context lsp.InlineValueContext + +---Inline value options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueRegistrationOptions: lsp.InlineValueOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in inlay hint requests. +--- +---@since 3.17.0 +---@class lsp.InlayHintParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inlay hints should be computed. +---@field range lsp.Range + +---Inlay hint information. +--- +---@since 3.17.0 +---@class lsp.InlayHint +---The position of this hint. +---@field position lsp.Position +---The label of this hint. A human readable string or an array of +---InlayHintLabelPart label parts. +--- +---*Note* that neither the string nor the label part can be empty. +---@field label string|lsp.InlayHintLabelPart[] +---The kind of this hint. Can be omitted in which case the client +---should fall back to a reasonable default. +---@field kind? lsp.InlayHintKind +---Optional text edits that are performed when accepting this inlay hint. +--- +---*Note* that edits are expected to change the document so that the inlay +---hint (or its nearest variant) is now part of the document and the inlay +---hint itself is now obsolete. +---@field textEdits? lsp.TextEdit[] +---The tooltip text when you hover over this item. +---@field tooltip? string|lsp.MarkupContent +---Render padding before the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingLeft? boolean +---Render padding after the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingRight? boolean +---A data entry field that is preserved on an inlay hint between +---a `textDocument/inlayHint` and a `inlayHint/resolve` request. +---@field data? lsp.LSPAny + +---Inlay hint options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintRegistrationOptions: lsp.InlayHintOptions, lsp.StaticRegistrationOptions + +---Parameters of the document diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The additional identifier provided during registration. +---@field identifier? string +---The result id of a previous response if provided. +---@field previousResultId? string + +---A partial result for a document diagnostic report. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticReportPartialResult +---@field relatedDocuments table + +---Cancellation data returned from a diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DiagnosticServerCancellationData +---@field retriggerRequest boolean + +---Diagnostic registration options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters of the workspace diagnostic request. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticParams +---The additional identifier provided during registration. +---@field identifier? string +---The currently known diagnostic reports with their +---previous result ids. +---@field previousResultIds lsp.PreviousResultId[] + +---A workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReport +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---A partial result for a workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReportPartialResult +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---The params sent in an open notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidOpenNotebookDocumentParams +---The notebook document that got opened. +---@field notebookDocument lsp.NotebookDocument +---The text documents that represent the content +---of a notebook cell. +---@field cellTextDocuments lsp.TextDocumentItem[] + +---The params sent in a change notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidChangeNotebookDocumentParams +---The notebook document that did change. The version number points +---to the version after all provided changes have been applied. If +---only the text document content of a cell changes the notebook version +---doesn't necessarily have to change. +---@field notebookDocument lsp.VersionedNotebookDocumentIdentifier +---The actual changes to the notebook document. +--- +---The changes describe single state changes to the notebook document. +---So if there are two changes c1 (at array index 0) and c2 (at array +---index 1) for a notebook in state S then c1 moves the notebook from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and +---c2 is computed on the state S'. +--- +---To mirror the content of a notebook using change events use the following approach: +---- start with the same initial content +---- apply the 'notebookDocument/didChange' notifications in the order you receive them. +---- apply the `NotebookChangeEvent`s in a single notification in the order +--- you receive them. +---@field change lsp.NotebookDocumentChangeEvent + +---The params sent in a save notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidSaveNotebookDocumentParams +---The notebook document that got saved. +---@field notebookDocument lsp.NotebookDocumentIdentifier + +---The params sent in a close notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidCloseNotebookDocumentParams +---The notebook document that got closed. +---@field notebookDocument lsp.NotebookDocumentIdentifier +---The text documents that represent the content +---of a notebook cell that got closed. +---@field cellTextDocuments lsp.TextDocumentIdentifier[] + +---A parameter literal used in inline completion requests. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---Additional information about the context in which inline completions were +---requested. +---@field context lsp.InlineCompletionContext + +---Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionList +---The inline completion items +---@field items lsp.InlineCompletionItem[] + +---An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionItem +---The text to replace the range with. Must be set. +---@field insertText string|lsp.StringValue +---A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. +---@field filterText? string +---The range to replace. Must begin and end on the same line. +---@field range? lsp.Range +---An optional {@link Command} that is executed *after* inserting this completion. +---@field command? lsp.Command + +---Inline completion options used during static or dynamic registration. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionRegistrationOptions: lsp.InlineCompletionOptions, lsp.StaticRegistrationOptions + +---@class lsp.RegistrationParams +---@field registrations lsp.Registration[] + +---@class lsp.UnregistrationParams +---@field unregisterations lsp.Unregistration[] + +---@class lsp.InitializeParams: lsp._InitializeParams + +---The result returned from an initialize request. +---@class lsp.InitializeResult +---The capabilities the language server provides. +---@field capabilities lsp.ServerCapabilities +---Information about the server. +--- +---@since 3.15.0 +---@field serverInfo? anonym1 + +---The data type of the ResponseError if the +---initialize request fails. +---@class lsp.InitializeError +---Indicates whether the client execute the following retry logic: +---(1) show the message provided by the ResponseError to the user +---(2) user selects retry or cancel +---(3) if user selected retry the initialize method is sent again. +---@field retry boolean + +---@class lsp.InitializedParams + +---The parameters of a change configuration notification. +---@class lsp.DidChangeConfigurationParams +---The actual changed settings +---@field settings lsp.LSPAny + +---@class lsp.DidChangeConfigurationRegistrationOptions +---@field section? string|string[] + +---The parameters of a notification message. +---@class lsp.ShowMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---@class lsp.ShowMessageRequestParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string +---The message action items to present. +---@field actions? lsp.MessageActionItem[] + +---@class lsp.MessageActionItem +---A short title like 'Retry', 'Open Log' etc. +---@field title string + +---The log message parameters. +---@class lsp.LogMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---The parameters sent in an open text document notification +---@class lsp.DidOpenTextDocumentParams +---The document that was opened. +---@field textDocument lsp.TextDocumentItem + +---The change text document notification's parameters. +---@class lsp.DidChangeTextDocumentParams +---The document that did change. The version number points +---to the version after all provided content changes have +---been applied. +---@field textDocument lsp.VersionedTextDocumentIdentifier +---The actual content changes. The content changes describe single state changes +---to the document. So if there are two content changes c1 (at array index 0) and +---c2 (at array index 1) for a document in state S then c1 moves the document from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed +---on the state S'. +--- +---To mirror the content of a document using change events use the following approach: +---- start with the same initial content +---- apply the 'textDocument/didChange' notifications in the order you receive them. +---- apply the `TextDocumentContentChangeEvent`s in a single notification in the order +--- you receive them. +---@field contentChanges lsp.TextDocumentContentChangeEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.TextDocumentChangeRegistrationOptions: lsp.TextDocumentRegistrationOptions +---How documents are synced to the server. +---@field syncKind lsp.TextDocumentSyncKind + +---The parameters sent in a close text document notification +---@class lsp.DidCloseTextDocumentParams +---The document that was closed. +---@field textDocument lsp.TextDocumentIdentifier + +---The parameters sent in a save text document notification +---@class lsp.DidSaveTextDocumentParams +---The document that was saved. +---@field textDocument lsp.TextDocumentIdentifier +---Optional the content when saved. Depends on the includeText value +---when the save notification was requested. +---@field text? string + +---Save registration options. +---@class lsp.TextDocumentSaveRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters sent in a will save text document notification. +---@class lsp.WillSaveTextDocumentParams +---The document that will be saved. +---@field textDocument lsp.TextDocumentIdentifier +---The 'TextDocumentSaveReason'. +---@field reason lsp.TextDocumentSaveReason + +---A text edit applicable to a text document. +---@class lsp.TextEdit +---The range of the text document to be manipulated. To insert +---text into a document create a range where start === end. +---@field range lsp.Range +---The string to be inserted. For delete operations use an +---empty string. +---@field newText string + +---The watched files change notification's parameters. +---@class lsp.DidChangeWatchedFilesParams +---The actual file events. +---@field changes lsp.FileEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.DidChangeWatchedFilesRegistrationOptions +---The watchers to register. +---@field watchers lsp.FileSystemWatcher[] + +---The publish diagnostic notification's parameters. +---@class lsp.PublishDiagnosticsParams +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---Optional the version number of the document the diagnostics are published for. +--- +---@since 3.15.0 +---@field version? integer +---An array of diagnostic information items. +---@field diagnostics lsp.Diagnostic[] + +---Completion parameters +---@class lsp.CompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---The completion context. This is only available it the client specifies +---to send this using the client capability `textDocument.completion.contextSupport === true` +---@field context? lsp.CompletionContext + +---A completion item represents a text snippet that is +---proposed to complete text that is being typed. +---@class lsp.CompletionItem +---The label of this completion item. +--- +---The label property is also by default the text that +---is inserted when selecting this completion. +--- +---If label details are provided the label itself should +---be an unqualified name of the completion item. +---@field label string +---Additional details for the label +--- +---@since 3.17.0 +---@field labelDetails? lsp.CompletionItemLabelDetails +---The kind of this completion item. Based of the kind +---an icon is chosen by the editor. +---@field kind? lsp.CompletionItemKind +---Tags for this completion item. +--- +---@since 3.15.0 +---@field tags? lsp.CompletionItemTag[] +---A human-readable string with additional information +---about this item, like type or symbol information. +---@field detail? string +---A human-readable string that represents a doc-comment. +---@field documentation? string|lsp.MarkupContent +---Indicates if this item is deprecated. +---@deprecated Use `tags` instead. +---@field deprecated? boolean +---Select this item when showing. +--- +---*Note* that only one completion item can be selected and that the +---tool / client decides which item that is. The rule is that the *first* +---item of those that match best is selected. +---@field preselect? boolean +---A string that should be used when comparing this item +---with other items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field sortText? string +---A string that should be used when filtering a set of +---completion items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field filterText? string +---A string that should be inserted into a document when selecting +---this completion. When `falsy` the {@link CompletionItem.label label} +---is used. +--- +---The `insertText` is subject to interpretation by the client side. +---Some tools might not take the string literally. For example +---VS Code when code complete is requested in this example +---`con` and a completion item with an `insertText` of +---`console` is provided it will only insert `sole`. Therefore it is +---recommended to use `textEdit` instead since it avoids additional client +---side interpretation. +---@field insertText? string +---The format of the insert text. The format applies to both the +---`insertText` property and the `newText` property of a provided +---`textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. +--- +---Please note that the insertTextFormat doesn't apply to +---`additionalTextEdits`. +---@field insertTextFormat? lsp.InsertTextFormat +---How whitespace and indentation is handled during completion +---item insertion. If not provided the clients default value depends on +---the `textDocument.completion.insertTextMode` client capability. +--- +---@since 3.16.0 +---@field insertTextMode? lsp.InsertTextMode +---An {@link TextEdit edit} which is applied to a document when selecting +---this completion. When an edit is provided the value of +---{@link CompletionItem.insertText insertText} is ignored. +--- +---Most editors support two different operations when accepting a completion +---item. One is to insert a completion text and the other is to replace an +---existing text with a completion text. Since this can usually not be +---predetermined by a server it can report both ranges. Clients need to +---signal support for `InsertReplaceEdits` via the +---`textDocument.completion.insertReplaceSupport` client capability +---property. +--- +---*Note 1:* The text edit's range as well as both ranges from an insert +---replace edit must be a [single line] and they must contain the position +---at which completion has been requested. +---*Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range +---must be a prefix of the edit's replace range, that means it must be +---contained and starting at the same position. +--- +---@since 3.16.0 additional type `InsertReplaceEdit` +---@field textEdit? lsp.TextEdit|lsp.InsertReplaceEdit +---The edit text used if the completion item is part of a CompletionList and +---CompletionList defines an item default for the text edit range. +--- +---Clients will only honor this property if they opt into completion list +---item defaults using the capability `completionList.itemDefaults`. +--- +---If not provided and a list's default range is provided the label +---property is used as a text. +--- +---@since 3.17.0 +---@field textEditText? string +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this completion. Edits must not overlap (including the same insert position) +---with the main {@link CompletionItem.textEdit edit} nor with themselves. +--- +---Additional text edits should be used to change text unrelated to the current cursor position +---(for example adding an import statement at the top of the file if the completion item will +---insert an unqualified type). +---@field additionalTextEdits? lsp.TextEdit[] +---An optional set of characters that when pressed while this completion is active will accept it first and +---then type that character. *Note* that all commit characters should have `length=1` and that superfluous +---characters will be ignored. +---@field commitCharacters? string[] +---An optional {@link Command command} that is executed *after* inserting this completion. *Note* that +---additional modifications to the current document should be described with the +---{@link CompletionItem.additionalTextEdits additionalTextEdits}-property. +---@field command? lsp.Command +---A data entry field that is preserved on a completion item between a +---{@link CompletionRequest} and a {@link CompletionResolveRequest}. +---@field data? lsp.LSPAny + +---Represents a collection of {@link CompletionItem completion items} to be presented +---in the editor. +---@class lsp.CompletionList +---This list it not complete. Further typing results in recomputing this list. +--- +---Recomputed lists have all their items replaced (not appended) in the +---incomplete completion sessions. +---@field isIncomplete boolean +---In many cases the items of an actual completion result share the same +---value for properties like `commitCharacters` or the range of a text +---edit. A completion list can therefore define item defaults which will +---be used if a completion item itself doesn't specify the value. +--- +---If a completion list specifies a default value and a completion item +---also specifies a corresponding value the one from the item is used. +--- +---Servers are only allowed to return default values if the client +---signals support for this via the `completionList.itemDefaults` +---capability. +--- +---@since 3.17.0 +---@field itemDefaults? anonym3 +---The completion items. +---@field items lsp.CompletionItem[] + +---Registration options for a {@link CompletionRequest}. +---@class lsp.CompletionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link HoverRequest}. +---@class lsp.HoverParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a hover request. +---@class lsp.Hover +---The hover's content +---@field contents lsp.MarkupContent|lsp.MarkedString|lsp.MarkedString[] +---An optional range inside the text document that is used to +---visualize the hover, e.g. by changing the background color. +---@field range? lsp.Range + +---Registration options for a {@link HoverRequest}. +---@class lsp.HoverRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---The signature help context. This is only available if the client specifies +---to send this using the client capability `textDocument.signatureHelp.contextSupport === true` +--- +---@since 3.15.0 +---@field context? lsp.SignatureHelpContext + +---Signature help represents the signature of something +---callable. There can be multiple signature but only one +---active and only one active parameter. +---@class lsp.SignatureHelp +---One or more signatures. +---@field signatures lsp.SignatureInformation[] +---The active signature. If omitted or the value lies outside the +---range of `signatures` the value defaults to zero or is ignored if +---the `SignatureHelp` has no signatures. +--- +---Whenever possible implementors should make an active decision about +---the active signature and shouldn't rely on a default value. +--- +---In future version of the protocol this property might become +---mandatory to better express this. +---@field activeSignature? uinteger +---The active parameter of the active signature. If omitted or the value +---lies outside the range of `signatures[activeSignature].parameters` +---defaults to 0 if the active signature has parameters. If +---the active signature has no parameters it is ignored. +---In future version of the protocol this property might become +---mandatory to better express the active parameter if the +---active signature does have any. +---@field activeParameter? uinteger + +---Registration options for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DefinitionRequest}. +---@class lsp.DefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Registration options for a {@link DefinitionRequest}. +---@class lsp.DefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link ReferencesRequest}. +---@class lsp.ReferenceParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---@field context lsp.ReferenceContext + +---Registration options for a {@link ReferencesRequest}. +---@class lsp.ReferenceRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---A document highlight is a range inside a text document which deserves +---special attention. Usually a document highlight is visualized by changing +---the background color of its range. +---@class lsp.DocumentHighlight +---The range this highlight applies to. +---@field range lsp.Range +---The highlight kind, default is {@link DocumentHighlightKind.Text text}. +---@field kind? lsp.DocumentHighlightKind + +---Registration options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents information about programming constructs like variables, classes, +---interfaces etc. +---@class lsp.SymbolInformation: lsp.BaseSymbolInformation +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The location of this symbol. The location's range is used by a tool +---to reveal the location in the editor. If the symbol is selected in the +---tool the range's start information is used to position the cursor. So +---the range usually spans more than the actual symbol's name and does +---normally include things like visibility modifiers. +--- +---The range doesn't have to denote a node range in the sense of an abstract +---syntax tree. It can therefore not be used to re-construct a hierarchy of +---the symbols. +---@field location lsp.Location + +---Represents programming constructs like variables, classes, interfaces etc. +---that appear in a document. Document symbols can be hierarchical and they +---have two ranges: one that encloses its definition and one that points to +---its most interesting range, e.g. the range of an identifier. +---@class lsp.DocumentSymbol +---The name of this symbol. Will be displayed in the user interface and therefore must not be +---an empty string or a string only consisting of white spaces. +---@field name string +---More detail for this symbol, e.g the signature of a function. +---@field detail? string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this document symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to determine if the clients cursor is +---inside the symbol to reveal in the symbol in the UI. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. +---Must be contained by the `range`. +---@field selectionRange lsp.Range +---Children of this symbol, e.g. properties of a class. +---@field children? lsp.DocumentSymbol[] + +---Registration options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link CodeActionRequest}. +---@class lsp.CodeActionParams +---The document in which the command was invoked. +---@field textDocument lsp.TextDocumentIdentifier +---The range for which the command was invoked. +---@field range lsp.Range +---Context carrying additional information. +---@field context lsp.CodeActionContext + +---Represents a reference to a command. Provides a title which +---will be used to represent a command in the UI and, optionally, +---an array of arguments which will be passed to the command handler +---function when invoked. +---@class lsp.Command +---Title of the command, like `save`. +---@field title string +---The identifier of the actual command handler. +---@field command string +---Arguments that the command handler should be +---invoked with. +---@field arguments? lsp.LSPAny[] + +---A code action represents a change that can be performed in code, e.g. to fix a problem or +---to refactor code. +--- +---A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. +---@class lsp.CodeAction +---A short, human-readable, title for this code action. +---@field title string +---The kind of the code action. +--- +---Used to filter code actions. +---@field kind? lsp.CodeActionKind +---The diagnostics that this code action resolves. +---@field diagnostics? lsp.Diagnostic[] +---Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted +---by keybindings. +--- +---A quick fix should be marked preferred if it properly addresses the underlying error. +---A refactoring should be marked preferred if it is the most reasonable choice of actions to take. +--- +---@since 3.15.0 +---@field isPreferred? boolean +---Marks that the code action cannot currently be applied. +--- +---Clients should follow the following guidelines regarding disabled code actions: +--- +--- - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) +--- code action menus. +--- +--- - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type +--- of code action, such as refactorings. +--- +--- - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) +--- that auto applies a code action and only disabled code actions are returned, the client should show the user an +--- error message with `reason` in the editor. +--- +---@since 3.16.0 +---@field disabled? anonym4 +---The workspace edit this code action performs. +---@field edit? lsp.WorkspaceEdit +---A command this code action executes. If a code action +---provides an edit and a command, first the edit is +---executed and then the command. +---@field command? lsp.Command +---A data entry field that is preserved on a code action between +---a `textDocument/codeAction` and a `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeActionRequest}. +---@class lsp.CodeActionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolParams +---A query string to filter symbols by. Clients may send an empty +---string here to request all symbols. +---@field query string + +---A special workspace symbol that supports locations without a range. +--- +---See also SymbolInformation. +--- +---@since 3.17.0 +---@class lsp.WorkspaceSymbol: lsp.BaseSymbolInformation +---The location of the symbol. Whether a server is allowed to +---return a location without a range depends on the client +---capability `workspace.symbol.resolveSupport`. +--- +---See SymbolInformation#location for more details. +---@field location lsp.Location|anonym5 +---A data entry field that is preserved on a workspace symbol between a +---workspace symbol request and a workspace symbol resolve request. +---@field data? lsp.LSPAny + +---Registration options for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolRegistrationOptions: lsp.WorkspaceSymbolOptions + +---The parameters of a {@link CodeLensRequest}. +---@class lsp.CodeLensParams +---The document to request code lens for. +---@field textDocument lsp.TextDocumentIdentifier + +---A code lens represents a {@link Command command} that should be shown along with +---source text, like the number of references, a way to run tests, etc. +--- +---A code lens is _unresolved_ when no command is associated to it. For performance +---reasons the creation of a code lens and resolving should be done in two stages. +---@class lsp.CodeLens +---The range in which this code lens is valid. Should only span a single line. +---@field range lsp.Range +---The command this code lens represents. +---@field command? lsp.Command +---A data entry field that is preserved on a code lens item between +---a {@link CodeLensRequest} and a [CodeLensResolveRequest] +---(#CodeLensResolveRequest) +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeLensRequest}. +---@class lsp.CodeLensRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkParams +---The document to provide document links for. +---@field textDocument lsp.TextDocumentIdentifier + +---A document link is a range in a text document that links to an internal or external resource, like another +---text document or a web site. +---@class lsp.DocumentLink +---The range this link applies to. +---@field range lsp.Range +---The uri this link points to. If missing a resolve request is sent later. +---@field target? lsp.URI +---The tooltip text when you hover over this link. +--- +---If a tooltip is provided, is will be displayed in a string that includes instructions on how to +---trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, +---user settings, and localization. +--- +---@since 3.15.0 +---@field tooltip? string +---A data entry field that is preserved on a document link between a +---DocumentLinkRequest and a DocumentLinkResolveRequest. +---@field data? lsp.LSPAny + +---Registration options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The format options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The range to format +---@field range lsp.Range +---The format options +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The position around which the on type formatting should happen. +---This is not necessarily the exact position where the character denoted +---by the property `ch` got typed. +---@field position lsp.Position +---The character that has been typed that triggered the formatting +---on type request. That is not necessarily the last character that +---got inserted into the document since the client could auto insert +---characters as well (e.g. like automatic brace completion). +---@field ch string +---The formatting options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link RenameRequest}. +---@class lsp.RenameParams +---The document to rename. +---@field textDocument lsp.TextDocumentIdentifier +---The position at which this request was sent. +---@field position lsp.Position +---The new name of the symbol. If the given name is not valid the +---request must return a {@link ResponseError} with an +---appropriate message set. +---@field newName string + +---Registration options for a {@link RenameRequest}. +---@class lsp.RenameRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---@class lsp.PrepareRenameParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The parameters of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandParams +---The identifier of the actual command handler. +---@field command string +---Arguments that the command should be invoked with. +---@field arguments? lsp.LSPAny[] + +---Registration options for a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandRegistrationOptions: lsp.ExecuteCommandOptions + +---The parameters passed via an apply workspace edit request. +---@class lsp.ApplyWorkspaceEditParams +---An optional label of the workspace edit. This label is +---presented in the user interface for example on an undo +---stack to undo the workspace edit. +---@field label? string +---The edits to apply. +---@field edit lsp.WorkspaceEdit + +---The result returned from the apply workspace edit request. +--- +---@since 3.17 renamed from ApplyWorkspaceEditResponse +---@class lsp.ApplyWorkspaceEditResult +---Indicates whether the edit was applied or not. +---@field applied boolean +---An optional textual description for why the edit was not applied. +---This may be used by the server for diagnostic logging or to provide +---a suitable error for a request that triggered the edit. +---@field failureReason? string +---Depending on the client's failure handling strategy `failedChange` might +---contain the index of the change that failed. This property is only available +---if the client signals a `failureHandlingStrategy` in its client capabilities. +---@field failedChange? uinteger + +---@class lsp.WorkDoneProgressBegin +---@field kind "begin" +---Mandatory title of the progress operation. Used to briefly inform about +---the kind of operation being performed. +--- +---Examples: "Indexing" or "Linking dependencies". +---@field title string +---Controls if a cancel button should show to allow the user to cancel the +---long running operation. Clients that don't support cancellation are allowed +---to ignore the setting. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100]. +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressReport +---@field kind "report" +---Controls enablement state of a cancel button. +--- +---Clients that don't support cancellation or don't support controlling the button's +---enablement state are allowed to ignore the property. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100] +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressEnd +---@field kind "end" +---Optional, a final message indicating to for example indicate the outcome +---of the operation. +---@field message? string + +---@class lsp.SetTraceParams +---@field value lsp.TraceValues + +---@class lsp.LogTraceParams +---@field message string +---@field verbose? string + +---@class lsp.CancelParams +---The request id to cancel. +---@field id integer|string + +---@class lsp.ProgressParams +---The progress token provided by the client or server. +---@field token lsp.ProgressToken +---The progress data. +---@field value lsp.LSPAny + +---A parameter literal used in requests to pass a text document and a position inside that +---document. +---@class lsp.TextDocumentPositionParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The position inside the text document. +---@field position lsp.Position + +---@class lsp.WorkDoneProgressParams +---An optional token that a server can use to report work done progress. +---@field workDoneToken? lsp.ProgressToken + +---@class lsp.PartialResultParams +---An optional token that a server can use to report partial results (e.g. streaming) to +---the client. +---@field partialResultToken? lsp.ProgressToken + +---Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, +---including an origin range. +---@class lsp.LocationLink +---Span of the origin of this link. +--- +---Used as the underlined span for mouse interaction. Defaults to the word range at +---the definition position. +---@field originSelectionRange? lsp.Range +---The target resource identifier of this link. +---@field targetUri lsp.DocumentUri +---The full target range of this link. If the target for example is a symbol then target range is the +---range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to highlight the range in the editor. +---@field targetRange lsp.Range +---The range that should be selected and revealed when this link is being followed, e.g the name of a function. +---Must be contained by the `targetRange`. See also `DocumentSymbol#range` +---@field targetSelectionRange lsp.Range + +---A range in a text document expressed as (zero-based) start and end positions. +--- +---If you want to specify a range that contains a line including the line ending +---character(s) then use an end position denoting the start of the next line. +---For example: +---```ts +---{ +--- start: { line: 5, character: 23 } +--- end : { line 6, character : 0 } +---} +---``` +---@class lsp.Range +---The range's start position. +---@field start lsp.Position +---The range's end position. +---@field end lsp.Position + +---@class lsp.ImplementationOptions + +---Static registration options to be returned in the initialize +---request. +---@class lsp.StaticRegistrationOptions +---The id used to register the request. The id can be used to deregister +---the request again. See also Registration#id. +---@field id? string + +---@class lsp.TypeDefinitionOptions + +---The workspace folder change event. +---@class lsp.WorkspaceFoldersChangeEvent +---The array of added workspace folders +---@field added lsp.WorkspaceFolder[] +---The array of the removed workspace folders +---@field removed lsp.WorkspaceFolder[] + +---@class lsp.ConfigurationItem +---The scope to get the configuration section for. +---@field scopeUri? string +---The configuration section asked for. +---@field section? string + +---A literal to identify a text document in the client. +---@class lsp.TextDocumentIdentifier +---The text document's uri. +---@field uri lsp.DocumentUri + +---Represents a color in RGBA space. +---@class lsp.Color +---The red component of this color in the range [0-1]. +---@field red decimal +---The green component of this color in the range [0-1]. +---@field green decimal +---The blue component of this color in the range [0-1]. +---@field blue decimal +---The alpha component of this color in the range [0-1]. +---@field alpha decimal + +---@class lsp.DocumentColorOptions + +---@class lsp.FoldingRangeOptions + +---@class lsp.DeclarationOptions + +---Position in a text document expressed as zero-based line and character +---offset. Prior to 3.17 the offsets were always based on a UTF-16 string +---representation. So a string of the form `a𐐀b` the character offset of the +---character `a` is 0, the character offset of `𐐀` is 1 and the character +---offset of b is 3 since `𐐀` is represented using two code units in UTF-16. +---Since 3.17 clients and servers can agree on a different string encoding +---representation (e.g. UTF-8). The client announces it's supported encoding +---via the client capability [`general.positionEncodings`](#clientCapabilities). +---The value is an array of position encodings the client supports, with +---decreasing preference (e.g. the encoding at index `0` is the most preferred +---one). To stay backwards compatible the only mandatory encoding is UTF-16 +---represented via the string `utf-16`. The server can pick one of the +---encodings offered by the client and signals that encoding back to the +---client via the initialize result's property +---[`capabilities.positionEncoding`](#serverCapabilities). If the string value +---`utf-16` is missing from the client's capability `general.positionEncodings` +---servers can safely assume that the client supports UTF-16. If the server +---omits the position encoding in its initialize result the encoding defaults +---to the string value `utf-16`. Implementation considerations: since the +---conversion from one encoding into another requires the content of the +---file / line the conversion is best done where the file is read which is +---usually on the server side. +--- +---Positions are line end character agnostic. So you can not specify a position +---that denotes `\r|\n` or `\n|` where `|` represents the character offset. +--- +---@since 3.17.0 - support for negotiated position encoding. +---@class lsp.Position +---Line position in a document (zero-based). +--- +---If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. +---If a line number is negative, it defaults to 0. +---@field line uinteger +---Character offset on a line in a document (zero-based). +--- +---The meaning of this offset is determined by the negotiated +---`PositionEncodingKind`. +--- +---If the character value is greater than the line length it defaults back to the +---line length. +---@field character uinteger + +---@class lsp.SelectionRangeOptions + +---Call hierarchy options used during static registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensOptions +---The legend used by the server +---@field legend lsp.SemanticTokensLegend +---Server supports providing semantic tokens for a specific range +---of a document. +---@field range? boolean|anonym6 +---Server supports providing semantic tokens for a full document. +---@field full? boolean|anonym7 + +---@since 3.16.0 +---@class lsp.SemanticTokensEdit +---The start offset of the edit. +---@field start uinteger +---The count of elements to remove. +---@field deleteCount uinteger +---The elements to insert. +---@field data? uinteger[] + +---@class lsp.LinkedEditingRangeOptions + +---Represents information on a file/folder create. +--- +---@since 3.16.0 +---@class lsp.FileCreate +---A file:// URI for the location of the file/folder being created. +---@field uri string + +---Describes textual changes on a text document. A TextDocumentEdit describes all changes +---on a document version Si and after they are applied move the document to version Si+1. +---So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any +---kind of ordering. However the edits must be non overlapping. +---@class lsp.TextDocumentEdit +---The text document to change. +---@field textDocument lsp.OptionalVersionedTextDocumentIdentifier +---The edits to be applied. +--- +---@since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a +---client capability. +---@field edits lsp.TextEdit|lsp.AnnotatedTextEdit[] + +---Create file operation. +---@class lsp.CreateFile: lsp.ResourceOperation +---A create +---@field kind "create" +---The resource to create. +---@field uri lsp.DocumentUri +---Additional options +---@field options? lsp.CreateFileOptions + +---Rename file operation +---@class lsp.RenameFile: lsp.ResourceOperation +---A rename +---@field kind "rename" +---The old (existing) location. +---@field oldUri lsp.DocumentUri +---The new location. +---@field newUri lsp.DocumentUri +---Rename options. +---@field options? lsp.RenameFileOptions + +---Delete file operation +---@class lsp.DeleteFile: lsp.ResourceOperation +---A delete +---@field kind "delete" +---The file to delete. +---@field uri lsp.DocumentUri +---Delete options. +---@field options? lsp.DeleteFileOptions + +---Additional information that describes document changes. +--- +---@since 3.16.0 +---@class lsp.ChangeAnnotation +---A human-readable string describing the actual change. The string +---is rendered prominent in the user interface. +---@field label string +---A flag which indicates that user confirmation is needed +---before applying the change. +---@field needsConfirmation? boolean +---A human-readable string which is rendered less prominent in +---the user interface. +---@field description? string + +---A filter to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationFilter +---A Uri scheme like `file` or `untitled`. +---@field scheme? string +---The actual file operation pattern. +---@field pattern lsp.FileOperationPattern + +---Represents information on a file/folder rename. +--- +---@since 3.16.0 +---@class lsp.FileRename +---A file:// URI for the original location of the file/folder being renamed. +---@field oldUri string +---A file:// URI for the new location of the file/folder being renamed. +---@field newUri string + +---Represents information on a file/folder delete. +--- +---@since 3.16.0 +---@class lsp.FileDelete +---A file:// URI for the location of the file/folder being deleted. +---@field uri string + +---@class lsp.MonikerOptions + +---Type hierarchy options used during static registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyOptions + +---@since 3.17.0 +---@class lsp.InlineValueContext +---The stack frame (as a DAP Id) where the execution has stopped. +---@field frameId integer +---The document range where execution has stopped. +---Typically the end position of the range denotes the line where the inline values are shown. +---@field stoppedLocation lsp.Range + +---Provide inline value as text. +--- +---@since 3.17.0 +---@class lsp.InlineValueText +---The document range for which the inline value applies. +---@field range lsp.Range +---The text of the inline value. +---@field text string + +---Provide inline value through a variable lookup. +---If only a range is specified, the variable name will be extracted from the underlying document. +---An optional variable name can be used to override the extracted name. +--- +---@since 3.17.0 +---@class lsp.InlineValueVariableLookup +---The document range for which the inline value applies. +---The range is used to extract the variable name from the underlying document. +---@field range lsp.Range +---If specified the name of the variable to look up. +---@field variableName? string +---How to perform the lookup. +---@field caseSensitiveLookup boolean + +---Provide an inline value through an expression evaluation. +---If only a range is specified, the expression will be extracted from the underlying document. +---An optional expression can be used to override the extracted expression. +--- +---@since 3.17.0 +---@class lsp.InlineValueEvaluatableExpression +---The document range for which the inline value applies. +---The range is used to extract the evaluatable expression from the underlying document. +---@field range lsp.Range +---If specified the expression overrides the extracted expression. +---@field expression? string + +---Inline value options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueOptions + +---An inlay hint label part allows for interactive and composite labels +---of inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintLabelPart +---The value of this label part. +---@field value string +---The tooltip text when you hover over this label part. Depending on +---the client capability `inlayHint.resolveSupport` clients might resolve +---this property late using the resolve request. +---@field tooltip? string|lsp.MarkupContent +---An optional source code location that represents this +---label part. +--- +---The editor will use this location for the hover and for code navigation +---features: This part will become a clickable link that resolves to the +---definition of the symbol at the given location (not necessarily the +---location itself), it shows the hover that shows at the given location, +---and it shows a context menu with further code navigation commands. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field location? lsp.Location +---An optional command for this label part. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field command? lsp.Command + +---A `MarkupContent` literal represents a string value which content is interpreted base on its +---kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. +--- +---If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. +---See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---Here is an example how such a string can be constructed using JavaScript / TypeScript: +---```ts +---let markdown: MarkdownContent = { +--- kind: MarkupKind.Markdown, +--- value: [ +--- '# Header', +--- 'Some text', +--- '```typescript', +--- 'someCode();', +--- '```' +--- ].join('\n') +---}; +---``` +--- +---*Please Note* that clients might sanitize the return markdown. A client could decide to +---remove HTML from the markdown to avoid script execution. +---@class lsp.MarkupContent +---The type of the Markup +---@field kind lsp.MarkupKind +---The content itself +---@field value string + +---Inlay hint options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintOptions +---The server provides support to resolve additional +---information for an inlay hint item. +---@field resolveProvider? boolean + +---A full diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table + +---An unchanged diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table + +---A diagnostic report with a full set of problems. +--- +---@since 3.17.0 +---@class lsp.FullDocumentDiagnosticReport +---A full document diagnostic report. +---@field kind "full" +---An optional result id. If provided it will +---be sent on the next diagnostic request for the +---same document. +---@field resultId? string +---The actual items. +---@field items lsp.Diagnostic[] + +---A diagnostic report indicating that the last returned +---report is still accurate. +--- +---@since 3.17.0 +---@class lsp.UnchangedDocumentDiagnosticReport +---A document diagnostic report indicating +---no changes to the last result. A server can +---only return `unchanged` if result ids are +---provided. +---@field kind "unchanged" +---A result id which will be sent on the next +---diagnostic request for the same document. +---@field resultId string + +---Diagnostic options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticOptions +---An optional identifier under which the diagnostics are +---managed by the client. +---@field identifier? string +---Whether the language has inter file dependencies meaning that +---editing code in one file can result in a different diagnostic +---set in another file. Inter file dependencies are common for +---most programming languages and typically uncommon for linters. +---@field interFileDependencies boolean +---The server provides support for workspace diagnostics as well. +---@field workspaceDiagnostics boolean + +---A previous result id in a workspace pull request. +--- +---@since 3.17.0 +---@class lsp.PreviousResultId +---The URI for which the client knowns a +---result id. +---@field uri lsp.DocumentUri +---The value of the previous result id. +---@field value string + +---A notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocument +---The notebook document's uri. +---@field uri lsp.URI +---The type of the notebook. +---@field notebookType string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---Additional metadata stored with the notebook +---document. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---The cells of a notebook. +---@field cells lsp.NotebookCell[] + +---An item to transfer a text document from the client to the +---server. +---@class lsp.TextDocumentItem +---The text document's uri. +---@field uri lsp.DocumentUri +---The text document's language identifier. +---@field languageId string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---The content of the opened text document. +---@field text string + +---A versioned notebook document identifier. +--- +---@since 3.17.0 +---@class lsp.VersionedNotebookDocumentIdentifier +---The version number of this notebook document. +---@field version integer +---The notebook document's uri. +---@field uri lsp.URI + +---A change event for a notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentChangeEvent +---The changed meta data if any. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Changes to cells +---@field cells? anonym10 + +---A literal to identify a notebook document in the client. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentIdentifier +---The notebook document's uri. +---@field uri lsp.URI + +---Provides information about the context in which an inline completion was requested. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionContext +---Describes how the inline completion was triggered. +---@field triggerKind lsp.InlineCompletionTriggerKind +---Provides information about the currently selected item in the autocomplete widget if it is visible. +---@field selectedCompletionInfo? lsp.SelectedCompletionInfo + +---A string value used as a snippet is a template which allows to insert text +---and to control the editor cursor when insertion happens. +--- +---A snippet can define tab stops and placeholders with `$1`, `$2` +---and `${3:foo}`. `$0` defines the final tab stop, it defaults to +---the end of the snippet. Variables are defined with `$name` and +---`${name:default value}`. +--- +---@since 3.18.0 +---@proposed +---@class lsp.StringValue +---The kind of string value. +---@field kind "snippet" +---The snippet string. +---@field value string + +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionOptions + +---General parameters to register for a notification or to register a provider. +---@class lsp.Registration +---The id used to register the request. The id can be used to deregister +---the request again. +---@field id string +---The method / capability to register for. +---@field method string +---Options necessary for the registration. +---@field registerOptions? lsp.LSPAny + +---General parameters to unregister a request or notification. +---@class lsp.Unregistration +---The id used to unregister the request or notification. Usually an id +---provided during the register request. +---@field id string +---The method to unregister for. +---@field method string + +---The initialize parameters +---@class lsp._InitializeParams +---The process Id of the parent process that started +---the server. +--- +---Is `null` if the process has not been started by another process. +---If the parent process is not alive then the server should exit. +---@field processId integer|lsp.null +---Information about the client +--- +---@since 3.15.0 +---@field clientInfo? anonym11 +---The locale the client is currently showing the user interface +---in. This must not necessarily be the locale of the operating +---system. +--- +---Uses IETF language tags as the value's syntax +---(See https://en.wikipedia.org/wiki/IETF_language_tag) +--- +---@since 3.16.0 +---@field locale? string +---The rootPath of the workspace. Is null +---if no folder is open. +--- +---@deprecated in favour of rootUri. +---@field rootPath? string|lsp.null +---The rootUri of the workspace. Is null if no +---folder is open. If both `rootPath` and `rootUri` are set +---`rootUri` wins. +--- +---@deprecated in favour of workspaceFolders. +---@field rootUri lsp.DocumentUri|lsp.null +---The capabilities provided by the client (editor or tool) +---@field capabilities lsp.ClientCapabilities +---User provided initialization options. +---@field initializationOptions? lsp.LSPAny +---The initial trace setting. If omitted trace is disabled ('off'). +---@field trace? lsp.TraceValues + +---@class lsp.WorkspaceFoldersInitializeParams +---The workspace folders configured in the client when the server starts. +--- +---This property is only available if the client supports workspace folders. +---It can be `null` if the client supports workspace folders but none are +---configured. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFolder[]|lsp.null + +---Defines the capabilities provided by a language +---server. +---@class lsp.ServerCapabilities +---The position encoding the server picked from the encodings offered +---by the client via the client capability `general.positionEncodings`. +--- +---If the client didn't provide any position encodings the only valid +---value that a server can return is 'utf-16'. +--- +---If omitted it defaults to 'utf-16'. +--- +---@since 3.17.0 +---@field positionEncoding? lsp.PositionEncodingKind +---Defines how text documents are synced. Is either a detailed structure +---defining each notification or for backwards compatibility the +---TextDocumentSyncKind number. +---@field textDocumentSync? lsp.TextDocumentSyncOptions|lsp.TextDocumentSyncKind +---Defines how notebook documents are synced. +--- +---@since 3.17.0 +---@field notebookDocumentSync? lsp.NotebookDocumentSyncOptions|lsp.NotebookDocumentSyncRegistrationOptions +---The server provides completion support. +---@field completionProvider? lsp.CompletionOptions +---The server provides hover support. +---@field hoverProvider? boolean|lsp.HoverOptions +---The server provides signature help support. +---@field signatureHelpProvider? lsp.SignatureHelpOptions +---The server provides Goto Declaration support. +---@field declarationProvider? boolean|lsp.DeclarationOptions|lsp.DeclarationRegistrationOptions +---The server provides goto definition support. +---@field definitionProvider? boolean|lsp.DefinitionOptions +---The server provides Goto Type Definition support. +---@field typeDefinitionProvider? boolean|lsp.TypeDefinitionOptions|lsp.TypeDefinitionRegistrationOptions +---The server provides Goto Implementation support. +---@field implementationProvider? boolean|lsp.ImplementationOptions|lsp.ImplementationRegistrationOptions +---The server provides find references support. +---@field referencesProvider? boolean|lsp.ReferenceOptions +---The server provides document highlight support. +---@field documentHighlightProvider? boolean|lsp.DocumentHighlightOptions +---The server provides document symbol support. +---@field documentSymbolProvider? boolean|lsp.DocumentSymbolOptions +---The server provides code actions. CodeActionOptions may only be +---specified if the client states that it supports +---`codeActionLiteralSupport` in its initial `initialize` request. +---@field codeActionProvider? boolean|lsp.CodeActionOptions +---The server provides code lens. +---@field codeLensProvider? lsp.CodeLensOptions +---The server provides document link support. +---@field documentLinkProvider? lsp.DocumentLinkOptions +---The server provides color provider support. +---@field colorProvider? boolean|lsp.DocumentColorOptions|lsp.DocumentColorRegistrationOptions +---The server provides workspace symbol support. +---@field workspaceSymbolProvider? boolean|lsp.WorkspaceSymbolOptions +---The server provides document formatting. +---@field documentFormattingProvider? boolean|lsp.DocumentFormattingOptions +---The server provides document range formatting. +---@field documentRangeFormattingProvider? boolean|lsp.DocumentRangeFormattingOptions +---The server provides document formatting on typing. +---@field documentOnTypeFormattingProvider? lsp.DocumentOnTypeFormattingOptions +---The server provides rename support. RenameOptions may only be +---specified if the client states that it supports +---`prepareSupport` in its initial `initialize` request. +---@field renameProvider? boolean|lsp.RenameOptions +---The server provides folding provider support. +---@field foldingRangeProvider? boolean|lsp.FoldingRangeOptions|lsp.FoldingRangeRegistrationOptions +---The server provides selection range support. +---@field selectionRangeProvider? boolean|lsp.SelectionRangeOptions|lsp.SelectionRangeRegistrationOptions +---The server provides execute command support. +---@field executeCommandProvider? lsp.ExecuteCommandOptions +---The server provides call hierarchy support. +--- +---@since 3.16.0 +---@field callHierarchyProvider? boolean|lsp.CallHierarchyOptions|lsp.CallHierarchyRegistrationOptions +---The server provides linked editing range support. +--- +---@since 3.16.0 +---@field linkedEditingRangeProvider? boolean|lsp.LinkedEditingRangeOptions|lsp.LinkedEditingRangeRegistrationOptions +---The server provides semantic tokens support. +--- +---@since 3.16.0 +---@field semanticTokensProvider? lsp.SemanticTokensOptions|lsp.SemanticTokensRegistrationOptions +---The server provides moniker support. +--- +---@since 3.16.0 +---@field monikerProvider? boolean|lsp.MonikerOptions|lsp.MonikerRegistrationOptions +---The server provides type hierarchy support. +--- +---@since 3.17.0 +---@field typeHierarchyProvider? boolean|lsp.TypeHierarchyOptions|lsp.TypeHierarchyRegistrationOptions +---The server provides inline values. +--- +---@since 3.17.0 +---@field inlineValueProvider? boolean|lsp.InlineValueOptions|lsp.InlineValueRegistrationOptions +---The server provides inlay hints. +--- +---@since 3.17.0 +---@field inlayHintProvider? boolean|lsp.InlayHintOptions|lsp.InlayHintRegistrationOptions +---The server has support for pull model diagnostics. +--- +---@since 3.17.0 +---@field diagnosticProvider? lsp.DiagnosticOptions|lsp.DiagnosticRegistrationOptions +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@proposed +---@field inlineCompletionProvider? boolean|lsp.InlineCompletionOptions +---Workspace specific server capabilities. +---@field workspace? anonym12 +---Experimental server capabilities. +---@field experimental? lsp.LSPAny + +---A text document identifier to denote a specific version of a text document. +---@class lsp.VersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. +---@field version integer + +---Save options. +---@class lsp.SaveOptions +---The client is supposed to include the content on save. +---@field includeText? boolean + +---An event describing a file change. +---@class lsp.FileEvent +---The file's uri. +---@field uri lsp.DocumentUri +---The change type. +---@field type lsp.FileChangeType + +---@class lsp.FileSystemWatcher +---The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. +--- +---@since 3.17.0 support for relative patterns. +---@field globPattern lsp.GlobPattern +---The kind of events of interest. If omitted it defaults +---to WatchKind.Create | WatchKind.Change | WatchKind.Delete +---which is 7. +---@field kind? lsp.WatchKind + +---Represents a diagnostic, such as a compiler error or warning. Diagnostic objects +---are only valid in the scope of a resource. +---@class lsp.Diagnostic +---The range at which the message applies +---@field range lsp.Range +---The diagnostic's severity. Can be omitted. If omitted it is up to the +---client to interpret diagnostics as error, warning, info or hint. +---@field severity? lsp.DiagnosticSeverity +---The diagnostic's code, which usually appear in the user interface. +---@field code? integer|string +---An optional property to describe the error code. +---Requires the code field (above) to be present/not null. +--- +---@since 3.16.0 +---@field codeDescription? lsp.CodeDescription +---A human-readable string describing the source of this +---diagnostic, e.g. 'typescript' or 'super lint'. It usually +---appears in the user interface. +---@field source? string +---The diagnostic's message. It usually appears in the user interface +---@field message string +---Additional metadata about the diagnostic. +--- +---@since 3.15.0 +---@field tags? lsp.DiagnosticTag[] +---An array of related diagnostic information, e.g. when symbol-names within +---a scope collide all definitions can be marked via this property. +---@field relatedInformation? lsp.DiagnosticRelatedInformation[] +---A data entry field that is preserved between a `textDocument/publishDiagnostics` +---notification and `textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Contains additional information about the context in which a completion request is triggered. +---@class lsp.CompletionContext +---How the completion was triggered. +---@field triggerKind lsp.CompletionTriggerKind +---The trigger character (a single character) that has trigger code complete. +---Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` +---@field triggerCharacter? string + +---Additional details for a completion item label. +--- +---@since 3.17.0 +---@class lsp.CompletionItemLabelDetails +---An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, +---without any spacing. Should be used for function signatures and type annotations. +---@field detail? string +---An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used +---for fully qualified names and file paths. +---@field description? string + +---A special text edit to provide an insert and a replace operation. +--- +---@since 3.16.0 +---@class lsp.InsertReplaceEdit +---The string to be inserted. +---@field newText string +---The range if the insert is requested +---@field insert lsp.Range +---The range if the replace is requested. +---@field replace lsp.Range + +---Completion options. +---@class lsp.CompletionOptions +---Most tools trigger completion request automatically without explicitly requesting +---it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user +---starts to type an identifier. For example if the user types `c` in a JavaScript file +---code complete will automatically pop up present `console` besides others as a +---completion item. Characters that make up identifiers don't need to be listed here. +--- +---If code complete should automatically be trigger on characters not being valid inside +---an identifier (for example `.` in JavaScript) list them in `triggerCharacters`. +---@field triggerCharacters? string[] +---The list of all possible characters that commit a completion. This field can be used +---if clients don't support individual commit characters per completion item. See +---`ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` +--- +---If a server provides both `allCommitCharacters` and commit characters on an individual +---completion item the ones on the completion item win. +--- +---@since 3.2.0 +---@field allCommitCharacters? string[] +---The server provides support to resolve additional +---information for a completion item. +---@field resolveProvider? boolean +---The server supports the following `CompletionItem` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionItem? anonym13 + +---Hover options. +---@class lsp.HoverOptions + +---Additional information about the context in which a signature help request was triggered. +--- +---@since 3.15.0 +---@class lsp.SignatureHelpContext +---Action that caused signature help to be triggered. +---@field triggerKind lsp.SignatureHelpTriggerKind +---Character that caused signature help to be triggered. +--- +---This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` +---@field triggerCharacter? string +---`true` if signature help was already showing when it was triggered. +--- +---Retriggers occurs when the signature help is already active and can be caused by actions such as +---typing a trigger character, a cursor move, or document content changes. +---@field isRetrigger boolean +---The currently active `SignatureHelp`. +--- +---The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on +---the user navigating through available signatures. +---@field activeSignatureHelp? lsp.SignatureHelp + +---Represents the signature of something callable. A signature +---can have a label, like a function-name, a doc-comment, and +---a set of parameters. +---@class lsp.SignatureInformation +---The label of this signature. Will be shown in +---the UI. +---@field label string +---The human-readable doc-comment of this signature. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent +---The parameters of this signature. +---@field parameters? lsp.ParameterInformation[] +---The index of the active parameter. +--- +---If provided, this is used in place of `SignatureHelp.activeParameter`. +--- +---@since 3.16.0 +---@field activeParameter? uinteger + +---Server Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpOptions +---List of characters that trigger signature help automatically. +---@field triggerCharacters? string[] +---List of characters that re-trigger signature help. +--- +---These trigger characters are only active when signature help is already showing. All trigger characters +---are also counted as re-trigger characters. +--- +---@since 3.15.0 +---@field retriggerCharacters? string[] + +---Server Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionOptions + +---Value-object that contains additional information when +---requesting references. +---@class lsp.ReferenceContext +---Include the declaration of the current symbol. +---@field includeDeclaration boolean + +---Reference options. +---@class lsp.ReferenceOptions + +---Provider options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightOptions + +---A base for all symbol information. +---@class lsp.BaseSymbolInformation +---The name of this symbol. +---@field name string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---The name of the symbol containing this symbol. This information is for +---user interface purposes (e.g. to render a qualifier in the user interface +---if necessary). It can't be used to re-infer a hierarchy for the document +---symbols. +---@field containerName? string + +---Provider options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolOptions +---A human-readable string that is shown when multiple outlines trees +---are shown for the same document. +--- +---@since 3.16.0 +---@field label? string + +---Contains additional diagnostic information about the context in which +---a {@link CodeActionProvider.provideCodeActions code action} is run. +---@class lsp.CodeActionContext +---An array of diagnostics known on the client side overlapping the range provided to the +---`textDocument/codeAction` request. They are provided so that the server knows which +---errors are currently presented to the user for the given range. There is no guarantee +---that these accurately reflect the error state of the resource. The primary parameter +---to compute code actions is the provided range. +---@field diagnostics lsp.Diagnostic[] +---Requested kind of actions to return. +--- +---Actions not of this kind are filtered out by the client before being shown. So servers +---can omit computing them. +---@field only? lsp.CodeActionKind[] +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@field triggerKind? lsp.CodeActionTriggerKind + +---Provider options for a {@link CodeActionRequest}. +---@class lsp.CodeActionOptions +---CodeActionKinds that this server may return. +--- +---The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server +---may list out every specific kind they provide. +---@field codeActionKinds? lsp.CodeActionKind[] +---The server provides support to resolve additional +---information for a code action. +--- +---@since 3.16.0 +---@field resolveProvider? boolean + +---Server capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolOptions +---The server provides support to resolve additional +---information for a workspace symbol. +--- +---@since 3.17.0 +---@field resolveProvider? boolean + +---Code Lens provider options of a {@link CodeLensRequest}. +---@class lsp.CodeLensOptions +---Code lens has a resolve provider as well. +---@field resolveProvider? boolean + +---Provider options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkOptions +---Document links have a resolve provider as well. +---@field resolveProvider? boolean + +---Value-object describing what options formatting should use. +---@class lsp.FormattingOptions +---Size of a tab in spaces. +---@field tabSize uinteger +---Prefer spaces over tabs. +---@field insertSpaces boolean +---Trim trailing whitespace on a line. +--- +---@since 3.15.0 +---@field trimTrailingWhitespace? boolean +---Insert a newline character at the end of the file if one does not exist. +--- +---@since 3.15.0 +---@field insertFinalNewline? boolean +---Trim all newlines after the final newline at the end of the file. +--- +---@since 3.15.0 +---@field trimFinalNewlines? boolean + +---Provider options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingOptions + +---Provider options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingOptions + +---Provider options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingOptions +---A character on which formatting should be triggered, like `{`. +---@field firstTriggerCharacter string +---More trigger characters. +---@field moreTriggerCharacter? string[] + +---Provider options for a {@link RenameRequest}. +---@class lsp.RenameOptions +---Renames should be checked and tested before being executed. +--- +---@since version 3.12.0 +---@field prepareProvider? boolean + +---The server capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandOptions +---The commands to be executed on the server +---@field commands string[] + +---@since 3.16.0 +---@class lsp.SemanticTokensLegend +---The token types a server uses. +---@field tokenTypes string[] +---The token modifiers a server uses. +---@field tokenModifiers string[] + +---A text document identifier to optionally denote a specific version of a text document. +---@class lsp.OptionalVersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. If a versioned text document identifier +---is sent from the server to the client and the file is not open in the editor +---(the server has not received an open notification before) the server can send +---`null` to indicate that the version is unknown and the content on disk is the +---truth (as specified with document content ownership). +---@field version integer|lsp.null + +---A special text edit with an additional change annotation. +--- +---@since 3.16.0. +---@class lsp.AnnotatedTextEdit: lsp.TextEdit +---The actual identifier of the change annotation +---@field annotationId lsp.ChangeAnnotationIdentifier + +---A generic resource operation. +---@class lsp.ResourceOperation +---The resource operation kind. +---@field kind string +---An optional annotation identifier describing the operation. +--- +---@since 3.16.0 +---@field annotationId? lsp.ChangeAnnotationIdentifier + +---Options to create a file. +---@class lsp.CreateFileOptions +---Overwrite existing file. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignore if exists. +---@field ignoreIfExists? boolean + +---Rename file options +---@class lsp.RenameFileOptions +---Overwrite target if existing. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignores if target exists. +---@field ignoreIfExists? boolean + +---Delete file options +---@class lsp.DeleteFileOptions +---Delete the content recursively if a folder is denoted. +---@field recursive? boolean +---Ignore the operation if the file doesn't exist. +---@field ignoreIfNotExists? boolean + +---A pattern to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationPattern +---The glob pattern to match. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +---@field glob string +---Whether to match files or folders with this pattern. +--- +---Matches both if undefined. +---@field matches? lsp.FileOperationPatternKind +---Additional options used during matching. +---@field options? lsp.FileOperationPatternOptions + +---A full document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---An unchanged document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---A notebook cell. +--- +---A cell's document URI must be unique across ALL notebook +---cells and can therefore be used to uniquely identify a +---notebook cell or the cell's text document. +--- +---@since 3.17.0 +---@class lsp.NotebookCell +---The cell's kind +---@field kind lsp.NotebookCellKind +---The URI of the cell's text document +---content. +---@field document lsp.DocumentUri +---Additional metadata stored with the cell. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Additional execution summary information +---if supported by the client. +---@field executionSummary? lsp.ExecutionSummary + +---A change describing how to move a `NotebookCell` +---array from state S to S'. +--- +---@since 3.17.0 +---@class lsp.NotebookCellArrayChange +---The start oftest of the cell that changed. +---@field start uinteger +---The deleted cells +---@field deleteCount uinteger +---The new cells, if any +---@field cells? lsp.NotebookCell[] + +---Describes the currently selected completion item. +--- +---@since 3.18.0 +---@proposed +---@class lsp.SelectedCompletionInfo +---The range that will be replaced if this completion item is accepted. +---@field range lsp.Range +---The text the range will be replaced with if this completion is accepted. +---@field text string + +---Defines the capabilities provided by the client. +---@class lsp.ClientCapabilities +---Workspace specific client capabilities. +---@field workspace? lsp.WorkspaceClientCapabilities +---Text document specific client capabilities. +---@field textDocument? lsp.TextDocumentClientCapabilities +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@field notebookDocument? lsp.NotebookDocumentClientCapabilities +---Window specific client capabilities. +---@field window? lsp.WindowClientCapabilities +---General client capabilities. +--- +---@since 3.16.0 +---@field general? lsp.GeneralClientCapabilities +---Experimental client capabilities. +---@field experimental? lsp.LSPAny + +---@class lsp.TextDocumentSyncOptions +---Open and close notifications are sent to the server. If omitted open close notification should not +---be sent. +---@field openClose? boolean +---Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full +---and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. +---@field change? lsp.TextDocumentSyncKind +---If present will save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field willSave? boolean +---If present will save wait until requests are sent to the server. If omitted the request should not be +---sent. +---@field willSaveWaitUntil? boolean +---If present save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field save? boolean|lsp.SaveOptions + +---Options specific to a notebook plus its cells +---to be synced to the server. +--- +---If a selector provides a notebook document +---filter but no cell selector all cells of a +---matching notebook document will be synced. +--- +---If a selector provides no notebook document +---filter but only a cell selector all notebook +---document that contain at least one matching +---cell will be synced. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncOptions +---The notebooks to be synced +---@field notebookSelector anonym15|anonym17[] +---Whether save notification should be forwarded to +---the server. Will only be honored if mode === `notebook`. +---@field save? boolean + +---Registration options specific to a notebook. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncRegistrationOptions: lsp.NotebookDocumentSyncOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkspaceFoldersServerCapabilities +---The server has support for workspace folders +---@field supported? boolean +---Whether the server wants to receive workspace folder +---change notifications. +--- +---If a string is provided the string is treated as an ID +---under which the notification is registered on the client +---side. The ID can be used to unregister for these events +---using the `client/unregisterCapability` request. +---@field changeNotifications? string|boolean + +---Options for notifications/requests for user operations on files. +--- +---@since 3.16.0 +---@class lsp.FileOperationOptions +---The server is interested in receiving didCreateFiles notifications. +---@field didCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willCreateFiles requests. +---@field willCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didRenameFiles notifications. +---@field didRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willRenameFiles requests. +---@field willRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didDeleteFiles file notifications. +---@field didDelete? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willDeleteFiles file requests. +---@field willDelete? lsp.FileOperationRegistrationOptions + +---Structure to capture a description for an error code. +--- +---@since 3.16.0 +---@class lsp.CodeDescription +---An URI to open with more information about the diagnostic error. +---@field href lsp.URI + +---Represents a related message and source code location for a diagnostic. This should be +---used to point to code locations that cause or related to a diagnostics, e.g when duplicating +---a symbol in a scope. +---@class lsp.DiagnosticRelatedInformation +---The location of this related diagnostic information. +---@field location lsp.Location +---The message of this related diagnostic information. +---@field message string + +---Represents a parameter of a callable-signature. A parameter can +---have a label and a doc-comment. +---@class lsp.ParameterInformation +---The label of this parameter information. +--- +---Either a string or an inclusive start and exclusive end offsets within its containing +---signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 +---string representation as `Position` and `Range` does. +--- +---*Note*: a label of type string should be a substring of its containing signature label. +---Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. +---@field label string|{ [1]: uinteger, [2]: uinteger } +---The human-readable doc-comment of this parameter. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent + +---A notebook cell text document filter denotes a cell text +---document by different properties. +--- +---@since 3.17.0 +---@class lsp.NotebookCellTextDocumentFilter +---A filter that matches against the notebook +---containing the notebook cell. If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---A language id like `python`. +--- +---Will be matched against the language id of the +---notebook cell document. '*' matches every language. +---@field language? string + +---Matching options for the file operation pattern. +--- +---@since 3.16.0 +---@class lsp.FileOperationPatternOptions +---The pattern should be matched ignoring casing. +---@field ignoreCase? boolean + +---@class lsp.ExecutionSummary +---A strict monotonically increasing value +---indicating the execution order of a cell +---inside a notebook. +---@field executionOrder uinteger +---Whether the execution was successful or +---not if known by the client. +---@field success? boolean + +---Workspace specific client capabilities. +---@class lsp.WorkspaceClientCapabilities +---The client supports applying batch edits +---to the workspace by supporting the request +---'workspace/applyEdit' +---@field applyEdit? boolean +---Capabilities specific to `WorkspaceEdit`s. +---@field workspaceEdit? lsp.WorkspaceEditClientCapabilities +---Capabilities specific to the `workspace/didChangeConfiguration` notification. +---@field didChangeConfiguration? lsp.DidChangeConfigurationClientCapabilities +---Capabilities specific to the `workspace/didChangeWatchedFiles` notification. +---@field didChangeWatchedFiles? lsp.DidChangeWatchedFilesClientCapabilities +---Capabilities specific to the `workspace/symbol` request. +---@field symbol? lsp.WorkspaceSymbolClientCapabilities +---Capabilities specific to the `workspace/executeCommand` request. +---@field executeCommand? lsp.ExecuteCommandClientCapabilities +---The client has support for workspace folders. +--- +---@since 3.6.0 +---@field workspaceFolders? boolean +---The client supports `workspace/configuration` requests. +--- +---@since 3.6.0 +---@field configuration? boolean +---Capabilities specific to the semantic token requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field semanticTokens? lsp.SemanticTokensWorkspaceClientCapabilities +---Capabilities specific to the code lens requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field codeLens? lsp.CodeLensWorkspaceClientCapabilities +---The client has support for file notifications/requests for user operations on files. +--- +---Since 3.16.0 +---@field fileOperations? lsp.FileOperationClientCapabilities +---Capabilities specific to the inline values requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlineValue? lsp.InlineValueWorkspaceClientCapabilities +---Capabilities specific to the inlay hint requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlayHint? lsp.InlayHintWorkspaceClientCapabilities +---Capabilities specific to the diagnostic requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field diagnostics? lsp.DiagnosticWorkspaceClientCapabilities + +---Text document specific client capabilities. +---@class lsp.TextDocumentClientCapabilities +---Defines which synchronization capabilities the client supports. +---@field synchronization? lsp.TextDocumentSyncClientCapabilities +---Capabilities specific to the `textDocument/completion` request. +---@field completion? lsp.CompletionClientCapabilities +---Capabilities specific to the `textDocument/hover` request. +---@field hover? lsp.HoverClientCapabilities +---Capabilities specific to the `textDocument/signatureHelp` request. +---@field signatureHelp? lsp.SignatureHelpClientCapabilities +---Capabilities specific to the `textDocument/declaration` request. +--- +---@since 3.14.0 +---@field declaration? lsp.DeclarationClientCapabilities +---Capabilities specific to the `textDocument/definition` request. +---@field definition? lsp.DefinitionClientCapabilities +---Capabilities specific to the `textDocument/typeDefinition` request. +--- +---@since 3.6.0 +---@field typeDefinition? lsp.TypeDefinitionClientCapabilities +---Capabilities specific to the `textDocument/implementation` request. +--- +---@since 3.6.0 +---@field implementation? lsp.ImplementationClientCapabilities +---Capabilities specific to the `textDocument/references` request. +---@field references? lsp.ReferenceClientCapabilities +---Capabilities specific to the `textDocument/documentHighlight` request. +---@field documentHighlight? lsp.DocumentHighlightClientCapabilities +---Capabilities specific to the `textDocument/documentSymbol` request. +---@field documentSymbol? lsp.DocumentSymbolClientCapabilities +---Capabilities specific to the `textDocument/codeAction` request. +---@field codeAction? lsp.CodeActionClientCapabilities +---Capabilities specific to the `textDocument/codeLens` request. +---@field codeLens? lsp.CodeLensClientCapabilities +---Capabilities specific to the `textDocument/documentLink` request. +---@field documentLink? lsp.DocumentLinkClientCapabilities +---Capabilities specific to the `textDocument/documentColor` and the +---`textDocument/colorPresentation` request. +--- +---@since 3.6.0 +---@field colorProvider? lsp.DocumentColorClientCapabilities +---Capabilities specific to the `textDocument/formatting` request. +---@field formatting? lsp.DocumentFormattingClientCapabilities +---Capabilities specific to the `textDocument/rangeFormatting` request. +---@field rangeFormatting? lsp.DocumentRangeFormattingClientCapabilities +---Capabilities specific to the `textDocument/onTypeFormatting` request. +---@field onTypeFormatting? lsp.DocumentOnTypeFormattingClientCapabilities +---Capabilities specific to the `textDocument/rename` request. +---@field rename? lsp.RenameClientCapabilities +---Capabilities specific to the `textDocument/foldingRange` request. +--- +---@since 3.10.0 +---@field foldingRange? lsp.FoldingRangeClientCapabilities +---Capabilities specific to the `textDocument/selectionRange` request. +--- +---@since 3.15.0 +---@field selectionRange? lsp.SelectionRangeClientCapabilities +---Capabilities specific to the `textDocument/publishDiagnostics` notification. +---@field publishDiagnostics? lsp.PublishDiagnosticsClientCapabilities +---Capabilities specific to the various call hierarchy requests. +--- +---@since 3.16.0 +---@field callHierarchy? lsp.CallHierarchyClientCapabilities +---Capabilities specific to the various semantic token request. +--- +---@since 3.16.0 +---@field semanticTokens? lsp.SemanticTokensClientCapabilities +---Capabilities specific to the `textDocument/linkedEditingRange` request. +--- +---@since 3.16.0 +---@field linkedEditingRange? lsp.LinkedEditingRangeClientCapabilities +---Client capabilities specific to the `textDocument/moniker` request. +--- +---@since 3.16.0 +---@field moniker? lsp.MonikerClientCapabilities +---Capabilities specific to the various type hierarchy requests. +--- +---@since 3.17.0 +---@field typeHierarchy? lsp.TypeHierarchyClientCapabilities +---Capabilities specific to the `textDocument/inlineValue` request. +--- +---@since 3.17.0 +---@field inlineValue? lsp.InlineValueClientCapabilities +---Capabilities specific to the `textDocument/inlayHint` request. +--- +---@since 3.17.0 +---@field inlayHint? lsp.InlayHintClientCapabilities +---Capabilities specific to the diagnostic pull model. +--- +---@since 3.17.0 +---@field diagnostic? lsp.DiagnosticClientCapabilities +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@proposed +---@field inlineCompletion? lsp.InlineCompletionClientCapabilities + +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentClientCapabilities +---Capabilities specific to notebook document synchronization +--- +---@since 3.17.0 +---@field synchronization lsp.NotebookDocumentSyncClientCapabilities + +---@class lsp.WindowClientCapabilities +---It indicates whether the client supports server initiated +---progress using the `window/workDoneProgress/create` request. +--- +---The capability also controls Whether client supports handling +---of progress notifications. If set servers are allowed to report a +---`workDoneProgress` property in the request specific server +---capabilities. +--- +---@since 3.15.0 +---@field workDoneProgress? boolean +---Capabilities specific to the showMessage request. +--- +---@since 3.16.0 +---@field showMessage? lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the showDocument request. +--- +---@since 3.16.0 +---@field showDocument? lsp.ShowDocumentClientCapabilities + +---General client capabilities. +--- +---@since 3.16.0 +---@class lsp.GeneralClientCapabilities +---Client capability that signals how the client +---handles stale requests (e.g. a request +---for which the client will not process the response +---anymore since the information is outdated). +--- +---@since 3.17.0 +---@field staleRequestSupport? anonym18 +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@field regularExpressions? lsp.RegularExpressionsClientCapabilities +---Client capabilities specific to the client's markdown parser. +--- +---@since 3.16.0 +---@field markdown? lsp.MarkdownClientCapabilities +---The position encodings supported by the client. Client and server +---have to agree on the same position encoding to ensure that offsets +---(e.g. character position in a line) are interpreted the same on both +---sides. +--- +---To keep the protocol backwards compatible the following applies: if +---the value 'utf-16' is missing from the array of position encodings +---servers can assume that the client supports UTF-16. UTF-16 is +---therefore a mandatory encoding. +--- +---If omitted it defaults to ['utf-16']. +--- +---Implementation considerations: since the conversion from one encoding +---into another requires the content of the file / line the conversion +---is best done where the file is read which is usually on the server +---side. +--- +---@since 3.17.0 +---@field positionEncodings? lsp.PositionEncodingKind[] + +---A relative pattern is a helper to construct glob patterns that are matched +---relatively to a base URI. The common value for a `baseUri` is a workspace +---folder root, but it can be another absolute URI as well. +--- +---@since 3.17.0 +---@class lsp.RelativePattern +---A workspace folder or a base URI to which this pattern will be matched +---against relatively. +---@field baseUri lsp.WorkspaceFolder|lsp.URI +---The actual glob pattern; +---@field pattern lsp.Pattern + +---@class lsp.WorkspaceEditClientCapabilities +---The client supports versioned document changes in `WorkspaceEdit`s +---@field documentChanges? boolean +---The resource operations the client supports. Clients should at least +---support 'create', 'rename' and 'delete' files and folders. +--- +---@since 3.13.0 +---@field resourceOperations? lsp.ResourceOperationKind[] +---The failure handling strategy of a client if applying the workspace edit +---fails. +--- +---@since 3.13.0 +---@field failureHandling? lsp.FailureHandlingKind +---Whether the client normalizes line endings to the client specific +---setting. +---If set to `true` the client will normalize line ending characters +---in a workspace edit to the client-specified new line +---character. +--- +---@since 3.16.0 +---@field normalizesLineEndings? boolean +---Whether the client in general supports change annotations on text edits, +---create file, rename file and delete file changes. +--- +---@since 3.16.0 +---@field changeAnnotationSupport? anonym19 + +---@class lsp.DidChangeConfigurationClientCapabilities +---Did change configuration notification supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.DidChangeWatchedFilesClientCapabilities +---Did change watched files notification supports dynamic registration. Please note +---that the current protocol doesn't support static configuration for file changes +---from the server side. +---@field dynamicRegistration? boolean +---Whether the client has support for {@link RelativePattern relative pattern} +---or not. +--- +---@since 3.17.0 +---@field relativePatternSupport? boolean + +---Client capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolClientCapabilities +---Symbol request supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. +---@field symbolKind? anonym20 +---The client supports tags on `SymbolInformation`. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym21 +---The client support partial workspace symbols. The client will send the +---request `workspaceSymbol/resolve` to the server to resolve additional +---properties. +--- +---@since 3.17.0 +---@field resolveSupport? anonym22 + +---The client capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandClientCapabilities +---Execute command supports dynamic registration. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---semantic tokens currently shown. It should be used with absolute care +---and is useful for situation where a server for example detects a project +---wide change that requires such a calculation. +---@field refreshSupport? boolean + +---@since 3.16.0 +---@class lsp.CodeLensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---code lenses currently shown. It should be used with absolute care and is +---useful for situation where a server for example detect a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Capabilities relating to events from file operations by the user in the client. +--- +---These events do not come from the file system, they come from user operations +---like renaming a file in the UI. +--- +---@since 3.16.0 +---@class lsp.FileOperationClientCapabilities +---Whether the client supports dynamic registration for file requests/notifications. +---@field dynamicRegistration? boolean +---The client has support for sending didCreateFiles notifications. +---@field didCreate? boolean +---The client has support for sending willCreateFiles requests. +---@field willCreate? boolean +---The client has support for sending didRenameFiles notifications. +---@field didRename? boolean +---The client has support for sending willRenameFiles requests. +---@field willRename? boolean +---The client has support for sending didDeleteFiles notifications. +---@field didDelete? boolean +---The client has support for sending willDeleteFiles requests. +---@field willDelete? boolean + +---Client workspace capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inline values currently shown. It should be used with absolute care and is +---useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Client workspace capabilities specific to inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inlay hints currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Workspace client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---pulled diagnostics currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---@class lsp.TextDocumentSyncClientCapabilities +---Whether text document synchronization supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports sending will save notifications. +---@field willSave? boolean +---The client supports sending a will save request and +---waits for a response providing text edits which will +---be applied to the document before it is saved. +---@field willSaveWaitUntil? boolean +---The client supports did save notifications. +---@field didSave? boolean + +---Completion client capabilities +---@class lsp.CompletionClientCapabilities +---Whether completion supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `CompletionItem` specific +---capabilities. +---@field completionItem? anonym26 +---@field completionItemKind? anonym27 +---Defines how the client handles whitespace and indentation +---when accepting a completion item that uses multi line +---text in either `insertText` or `textEdit`. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---The client supports to send additional context information for a +---`textDocument/completion` request. +---@field contextSupport? boolean +---The client supports the following `CompletionList` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionList? anonym28 + +---@class lsp.HoverClientCapabilities +---Whether hover supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports the following content formats for the content +---property. The order describes the preferred format of the client. +---@field contentFormat? lsp.MarkupKind[] + +---Client Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpClientCapabilities +---Whether signature help supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `SignatureInformation` +---specific properties. +---@field signatureInformation? anonym30 +---The client supports to send additional context information for a +---`textDocument/signatureHelp` request. A client that opts into +---contextSupport will also support the `retriggerCharacters` on +---`SignatureHelpOptions`. +--- +---@since 3.15.0 +---@field contextSupport? boolean + +---@since 3.14.0 +---@class lsp.DeclarationClientCapabilities +---Whether declaration supports dynamic registration. If this is set to `true` +---the client supports the new `DeclarationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of declaration links. +---@field linkSupport? boolean + +---Client Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionClientCapabilities +---Whether definition supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Since 3.6.0 +---@class lsp.TypeDefinitionClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `TypeDefinitionRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---Since 3.14.0 +---@field linkSupport? boolean + +---@since 3.6.0 +---@class lsp.ImplementationClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `ImplementationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Client Capabilities for a {@link ReferencesRequest}. +---@class lsp.ReferenceClientCapabilities +---Whether references supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightClientCapabilities +---Whether document highlight supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolClientCapabilities +---Whether document symbol supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the +---`textDocument/documentSymbol` request. +---@field symbolKind? anonym31 +---The client supports hierarchical document symbols. +---@field hierarchicalDocumentSymbolSupport? boolean +---The client supports tags on `SymbolInformation`. Tags are supported on +---`DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym32 +---The client supports an additional label presented in the UI when +---registering a document symbol provider. +--- +---@since 3.16.0 +---@field labelSupport? boolean + +---The Client Capabilities of a {@link CodeActionRequest}. +---@class lsp.CodeActionClientCapabilities +---Whether code action supports dynamic registration. +---@field dynamicRegistration? boolean +---The client support code action literals of type `CodeAction` as a valid +---response of the `textDocument/codeAction` request. If the property is not +---set the request can only return `Command` literals. +--- +---@since 3.8.0 +---@field codeActionLiteralSupport? anonym34 +---Whether code action supports the `isPreferred` property. +--- +---@since 3.15.0 +---@field isPreferredSupport? boolean +---Whether code action supports the `disabled` property. +--- +---@since 3.16.0 +---@field disabledSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/codeAction` and a +---`codeAction/resolve` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean +---Whether the client supports resolving additional code action +---properties via a separate `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field resolveSupport? anonym35 +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---`CodeAction#edit` property by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---The client capabilities of a {@link CodeLensRequest}. +---@class lsp.CodeLensClientCapabilities +---Whether code lens supports dynamic registration. +---@field dynamicRegistration? boolean + +---The client capabilities of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkClientCapabilities +---Whether document link supports dynamic registration. +---@field dynamicRegistration? boolean +---Whether the client supports the `tooltip` property on `DocumentLink`. +--- +---@since 3.15.0 +---@field tooltipSupport? boolean + +---@class lsp.DocumentColorClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `DocumentColorRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingClientCapabilities +---Whether formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingClientCapabilities +---Whether range formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingClientCapabilities +---Whether on type formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.RenameClientCapabilities +---Whether rename supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports testing for validity of rename operations +---before execution. +--- +---@since 3.12.0 +---@field prepareSupport? boolean +---Client supports the default behavior result. +--- +---The value indicates the default behavior used by the +---client. +--- +---@since 3.16.0 +---@field prepareSupportDefaultBehavior? lsp.PrepareSupportDefaultBehavior +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---rename request's workspace edit by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---@class lsp.FoldingRangeClientCapabilities +---Whether implementation supports dynamic registration for folding range +---providers. If this is set to `true` the client supports the new +---`FoldingRangeRegistrationOptions` return value for the corresponding +---server capability as well. +---@field dynamicRegistration? boolean +---The maximum number of folding ranges that the client prefers to receive +---per document. The value serves as a hint, servers are free to follow the +---limit. +---@field rangeLimit? uinteger +---If set, the client signals that it only supports folding complete lines. +---If set, client will ignore specified `startCharacter` and `endCharacter` +---properties in a FoldingRange. +---@field lineFoldingOnly? boolean +---Specific options for the folding range kind. +--- +---@since 3.17.0 +---@field foldingRangeKind? anonym36 +---Specific options for the folding range. +--- +---@since 3.17.0 +---@field foldingRange? anonym37 + +---@class lsp.SelectionRangeClientCapabilities +---Whether implementation supports dynamic registration for selection range providers. If this is set to `true` +---the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server +---capability as well. +---@field dynamicRegistration? boolean + +---The publish diagnostic client capabilities. +---@class lsp.PublishDiagnosticsClientCapabilities +---Whether the clients accepts diagnostics with related information. +---@field relatedInformation? boolean +---Client supports the tag property to provide meta data about a diagnostic. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.15.0 +---@field tagSupport? anonym38 +---Whether the client interprets the version property of the +---`textDocument/publishDiagnostics` notification's parameter. +--- +---@since 3.15.0 +---@field versionSupport? boolean +---Client supports a codeDescription property +--- +---@since 3.16.0 +---@field codeDescriptionSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/publishDiagnostics` and +---`textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean + +---@since 3.16.0 +---@class lsp.CallHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Which requests the client supports and might send to the server +---depending on the server's capability. Please note that clients might not +---show semantic tokens or degrade some of the user experience if a range +---or full request is advertised by the client but not provided by the +---server. If for example the client capability `requests.full` and +---`request.range` are both set to true but the server only provides a +---range provider the client might not render a minimap correctly or might +---even decide to not show any semantic tokens at all. +---@field requests anonym41 +---The token types that the client supports. +---@field tokenTypes string[] +---The token modifiers that the client supports. +---@field tokenModifiers string[] +---The token formats the clients supports. +---@field formats lsp.TokenFormat[] +---Whether the client supports tokens that can overlap each other. +---@field overlappingTokenSupport? boolean +---Whether the client supports tokens that can span multiple lines. +---@field multilineTokenSupport? boolean +---Whether the client allows the server to actively cancel a +---semantic token request, e.g. supports returning +---LSPErrorCodes.ServerCancelled. If a server does the client +---needs to retrigger the request. +--- +---@since 3.17.0 +---@field serverCancelSupport? boolean +---Whether the client uses semantic tokens to augment existing +---syntax tokens. If set to `true` client side created syntax +---tokens and semantic tokens are both used for colorization. If +---set to `false` the client only uses the returned semantic tokens +---for colorization. +--- +---If the value is `undefined` then the client behavior is not +---specified. +--- +---@since 3.17.0 +---@field augmentsSyntaxTokens? boolean + +---Client capabilities for the linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRangeClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to the moniker request. +--- +---@since 3.16.0 +---@class lsp.MonikerClientCapabilities +---Whether moniker supports dynamic registration. If this is set to `true` +---the client supports the new `MonikerRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.17.0 +---@class lsp.TypeHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueClientCapabilities +---Whether implementation supports dynamic registration for inline value providers. +---@field dynamicRegistration? boolean + +---Inlay hint client capabilities. +--- +---@since 3.17.0 +---@class lsp.InlayHintClientCapabilities +---Whether inlay hints support dynamic registration. +---@field dynamicRegistration? boolean +---Indicates which properties a client can resolve lazily on an inlay +---hint. +---@field resolveSupport? anonym42 + +---Client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Whether the clients supports related documents for document diagnostic pulls. +---@field relatedDocumentSupport? boolean + +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@proposed +---@class lsp.InlineCompletionClientCapabilities +---Whether implementation supports dynamic registration for inline completion providers. +---@field dynamicRegistration? boolean + +---Notebook specific client capabilities. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncClientCapabilities +---Whether implementation supports dynamic registration. If this is +---set to `true` the client supports the new +---`(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports sending execution summary data per cell. +---@field executionSummarySupport? boolean + +---Show message request client capabilities +---@class lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the `MessageActionItem` type. +---@field messageActionItem? anonym43 + +---Client capabilities for the showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentClientCapabilities +---The client has support for the showDocument +---request. +---@field support boolean + +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@class lsp.RegularExpressionsClientCapabilities +---The engine's name. +---@field engine string +---The engine's version. +---@field version? string + +---Client capabilities specific to the used markdown parser. +--- +---@since 3.16.0 +---@class lsp.MarkdownClientCapabilities +---The name of the parser. +---@field parser string +---The version of the parser. +---@field version? string +---A list of HTML tags that the client allows / supports in +---Markdown. +--- +---@since 3.17.0 +---@field allowedTags? string[] + +---A set of predefined token types. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenTypes +---| "namespace" # namespace +---| "type" # type +---| "class" # class +---| "enum" # enum +---| "interface" # interface +---| "struct" # struct +---| "typeParameter" # typeParameter +---| "parameter" # parameter +---| "variable" # variable +---| "property" # property +---| "enumMember" # enumMember +---| "event" # event +---| "function" # function +---| "method" # method +---| "macro" # macro +---| "keyword" # keyword +---| "modifier" # modifier +---| "comment" # comment +---| "string" # string +---| "number" # number +---| "regexp" # regexp +---| "operator" # operator +---| "decorator" # decorator + +---A set of predefined token modifiers. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenModifiers +---| "declaration" # declaration +---| "definition" # definition +---| "readonly" # readonly +---| "static" # static +---| "deprecated" # deprecated +---| "abstract" # abstract +---| "async" # async +---| "modification" # modification +---| "documentation" # documentation +---| "defaultLibrary" # defaultLibrary + +---The document diagnostic report kinds. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReportKind +---| "full" # Full +---| "unchanged" # Unchanged + +---Predefined error codes. +---@alias lsp.ErrorCodes +---| -32700 # ParseError +---| -32600 # InvalidRequest +---| -32601 # MethodNotFound +---| -32602 # InvalidParams +---| -32603 # InternalError +---| -32002 # ServerNotInitialized +---| -32001 # UnknownErrorCode + +---@alias lsp.LSPErrorCodes +---| -32803 # RequestFailed +---| -32802 # ServerCancelled +---| -32801 # ContentModified +---| -32800 # RequestCancelled + +---A set of predefined range kinds. +---@alias lsp.FoldingRangeKind +---| "comment" # Comment +---| "imports" # Imports +---| "region" # Region + +---A symbol kind. +---@alias lsp.SymbolKind +---| 1 # File +---| 2 # Module +---| 3 # Namespace +---| 4 # Package +---| 5 # Class +---| 6 # Method +---| 7 # Property +---| 8 # Field +---| 9 # Constructor +---| 10 # Enum +---| 11 # Interface +---| 12 # Function +---| 13 # Variable +---| 14 # Constant +---| 15 # String +---| 16 # Number +---| 17 # Boolean +---| 18 # Array +---| 19 # Object +---| 20 # Key +---| 21 # Null +---| 22 # EnumMember +---| 23 # Struct +---| 24 # Event +---| 25 # Operator +---| 26 # TypeParameter + +---Symbol tags are extra annotations that tweak the rendering of a symbol. +--- +---@since 3.16 +---@alias lsp.SymbolTag +---| 1 # Deprecated + +---Moniker uniqueness level to define scope of the moniker. +--- +---@since 3.16.0 +---@alias lsp.UniquenessLevel +---| "document" # document +---| "project" # project +---| "group" # group +---| "scheme" # scheme +---| "global" # global + +---The moniker kind. +--- +---@since 3.16.0 +---@alias lsp.MonikerKind +---| "import" # import +---| "export" # export +---| "local" # local + +---Inlay hint kinds. +--- +---@since 3.17.0 +---@alias lsp.InlayHintKind +---| 1 # Type +---| 2 # Parameter + +---The message type +---@alias lsp.MessageType +---| 1 # Error +---| 2 # Warning +---| 3 # Info +---| 4 # Log + +---Defines how the host (editor) should sync +---document changes to the language server. +---@alias lsp.TextDocumentSyncKind +---| 0 # None +---| 1 # Full +---| 2 # Incremental + +---Represents reasons why a text document is saved. +---@alias lsp.TextDocumentSaveReason +---| 1 # Manual +---| 2 # AfterDelay +---| 3 # FocusOut + +---The kind of a completion entry. +---@alias lsp.CompletionItemKind +---| 1 # Text +---| 2 # Method +---| 3 # Function +---| 4 # Constructor +---| 5 # Field +---| 6 # Variable +---| 7 # Class +---| 8 # Interface +---| 9 # Module +---| 10 # Property +---| 11 # Unit +---| 12 # Value +---| 13 # Enum +---| 14 # Keyword +---| 15 # Snippet +---| 16 # Color +---| 17 # File +---| 18 # Reference +---| 19 # Folder +---| 20 # EnumMember +---| 21 # Constant +---| 22 # Struct +---| 23 # Event +---| 24 # Operator +---| 25 # TypeParameter + +---Completion item tags are extra annotations that tweak the rendering of a completion +---item. +--- +---@since 3.15.0 +---@alias lsp.CompletionItemTag +---| 1 # Deprecated + +---Defines whether the insert text in a completion item should be interpreted as +---plain text or a snippet. +---@alias lsp.InsertTextFormat +---| 1 # PlainText +---| 2 # Snippet + +---How whitespace and indentation is handled during completion +---item insertion. +--- +---@since 3.16.0 +---@alias lsp.InsertTextMode +---| 1 # asIs +---| 2 # adjustIndentation + +---A document highlight kind. +---@alias lsp.DocumentHighlightKind +---| 1 # Text +---| 2 # Read +---| 3 # Write + +---A set of predefined code action kinds +---@alias lsp.CodeActionKind +---| "" # Empty +---| "quickfix" # QuickFix +---| "refactor" # Refactor +---| "refactor.extract" # RefactorExtract +---| "refactor.inline" # RefactorInline +---| "refactor.rewrite" # RefactorRewrite +---| "source" # Source +---| "source.organizeImports" # SourceOrganizeImports +---| "source.fixAll" # SourceFixAll + +---@alias lsp.TraceValues +---| "off" # Off +---| "messages" # Messages +---| "verbose" # Verbose + +---Describes the content type that a client supports in various +---result literals like `Hover`, `ParameterInfo` or `CompletionItem`. +--- +---Please note that `MarkupKinds` must not start with a `$`. This kinds +---are reserved for internal usage. +---@alias lsp.MarkupKind +---| "plaintext" # PlainText +---| "markdown" # Markdown + +---Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. +--- +---@since 3.18.0 +---@proposed +---@alias lsp.InlineCompletionTriggerKind +---| 0 # Invoked +---| 1 # Automatic + +---A set of predefined position encoding kinds. +--- +---@since 3.17.0 +---@alias lsp.PositionEncodingKind +---| "utf-8" # UTF8 +---| "utf-16" # UTF16 +---| "utf-32" # UTF32 + +---The file event type +---@alias lsp.FileChangeType +---| 1 # Created +---| 2 # Changed +---| 3 # Deleted + +---@alias lsp.WatchKind +---| 1 # Create +---| 2 # Change +---| 4 # Delete + +---The diagnostic's severity. +---@alias lsp.DiagnosticSeverity +---| 1 # Error +---| 2 # Warning +---| 3 # Information +---| 4 # Hint + +---The diagnostic tags. +--- +---@since 3.15.0 +---@alias lsp.DiagnosticTag +---| 1 # Unnecessary +---| 2 # Deprecated + +---How a completion was triggered +---@alias lsp.CompletionTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # TriggerForIncompleteCompletions + +---How a signature help was triggered. +--- +---@since 3.15.0 +---@alias lsp.SignatureHelpTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # ContentChange + +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@alias lsp.CodeActionTriggerKind +---| 1 # Invoked +---| 2 # Automatic + +---A pattern kind describing if a glob pattern matches a file a folder or +---both. +--- +---@since 3.16.0 +---@alias lsp.FileOperationPatternKind +---| "file" # file +---| "folder" # folder + +---A notebook cell kind. +--- +---@since 3.17.0 +---@alias lsp.NotebookCellKind +---| 1 # Markup +---| 2 # Code + +---@alias lsp.ResourceOperationKind +---| "create" # Create +---| "rename" # Rename +---| "delete" # Delete + +---@alias lsp.FailureHandlingKind +---| "abort" # Abort +---| "transactional" # Transactional +---| "textOnlyTransactional" # TextOnlyTransactional +---| "undo" # Undo + +---@alias lsp.PrepareSupportDefaultBehavior +---| 1 # Identifier + +---@alias lsp.TokenFormat +---| "relative" # Relative + +---The definition of a symbol represented as one or many {@link Location locations}. +---For most programming languages there is only one location at which a symbol is +---defined. +--- +---Servers should prefer returning `DefinitionLink` over `Definition` if supported +---by the client. +---@alias lsp.Definition lsp.Location|lsp.Location[] + +---Information about where a symbol is defined. +--- +---Provides additional metadata over normal {@link Location location} definitions, including the range of +---the defining symbol +---@alias lsp.DefinitionLink lsp.LocationLink + +---LSP arrays. +---@since 3.17.0 +---@alias lsp.LSPArray lsp.LSPAny[] + +---The LSP any type. +---Please note that strictly speaking a property with the value `undefined` +---can't be converted into JSON preserving the property name. However for +---convenience it is allowed and assumed that all these properties are +---optional as well. +---@since 3.17.0 +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|integer|uinteger|decimal|boolean|lsp.null + +---The declaration of a symbol representation as one or many {@link Location locations}. +---@alias lsp.Declaration lsp.Location|lsp.Location[] + +---Information about where a symbol is declared. +--- +---Provides additional metadata over normal {@link Location location} declarations, including the range of +---the declaring symbol. +--- +---Servers should prefer returning `DeclarationLink` over `Declaration` if supported +---by the client. +---@alias lsp.DeclarationLink lsp.LocationLink + +---Inline value information can be provided by different means: +---- directly as a text value (class InlineValueText). +---- as a name to use for a variable lookup (class InlineValueVariableLookup) +---- as an evaluatable expression (class InlineValueEvaluatableExpression) +---The InlineValue types combines all inline value types into one type. +--- +---@since 3.17.0 +---@alias lsp.InlineValue lsp.InlineValueText|lsp.InlineValueVariableLookup|lsp.InlineValueEvaluatableExpression + +---The result of a document diagnostic pull request. A report can +---either be a full report containing all diagnostics for the +---requested document or an unchanged report indicating that nothing +---has changed in terms of diagnostics in comparison to the last +---pull request. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReport lsp.RelatedFullDocumentDiagnosticReport|lsp.RelatedUnchangedDocumentDiagnosticReport + +---@alias lsp.PrepareRenameResult lsp.Range|anonym44|anonym45 + +---A document selector is the combination of one or many document filters. +--- +---@sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`; +--- +---The use of a string as a document filter is deprecated @since 3.16.0. +---@alias lsp.DocumentSelector lsp.DocumentFilter[] + +---@alias lsp.ProgressToken integer|string + +---An identifier to refer to a change annotation stored with a workspace edit. +---@alias lsp.ChangeAnnotationIdentifier string + +---A workspace diagnostic document report. +--- +---@since 3.17.0 +---@alias lsp.WorkspaceDocumentDiagnosticReport lsp.WorkspaceFullDocumentDiagnosticReport|lsp.WorkspaceUnchangedDocumentDiagnosticReport + +---An event describing a change to a text document. If only a text is provided +---it is considered to be the full content of the document. +---@alias lsp.TextDocumentContentChangeEvent anonym46|anonym47 + +---MarkedString can be used to render human readable text. It is either a markdown string +---or a code-block that provides a language and a code snippet. The language identifier +---is semantically equal to the optional language identifier in fenced code blocks in GitHub +---issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---The pair of a language and a value is an equivalent to markdown: +---```${language} +---${value} +---``` +--- +---Note that markdown strings will be sanitized - that means html will be escaped. +---@deprecated use MarkupContent instead. +---@alias lsp.MarkedString string|anonym48 + +---A document filter describes a top level text document or +---a notebook cell document. +--- +---@since 3.17.0 - proposed support for NotebookCellTextDocumentFilter. +---@alias lsp.DocumentFilter lsp.TextDocumentFilter|lsp.NotebookCellTextDocumentFilter + +---LSP object definition. +---@since 3.17.0 +---@alias lsp.LSPObject table + +---The glob pattern. Either a string pattern or a relative pattern. +--- +---@since 3.17.0 +---@alias lsp.GlobPattern lsp.Pattern|lsp.RelativePattern + +---A document filter denotes a document by different properties like +---the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of +---its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}. +--- +---Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` +---@sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` +--- +---@since 3.17.0 +---@alias lsp.TextDocumentFilter anonym49|anonym50|anonym51 + +---A notebook document filter denotes a notebook document by +---different properties. The properties will be match +---against the notebook's URI (same as with documents) +--- +---@since 3.17.0 +---@alias lsp.NotebookDocumentFilter anonym52|anonym53|anonym54 + +---The glob pattern to watch relative to the base path. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@since 3.17.0 +---@alias lsp.Pattern string + +---@class anonym1 +---The name of the server as defined by the server. +---@field name string +---The server's version as defined by the server. +---@field version? string + +---@class anonym3 +---@field insert lsp.Range +---@field replace lsp.Range + +---@class anonym2 +---A default commit character set. +--- +---@since 3.17.0 +---@field commitCharacters? string[] +---A default edit range. +--- +---@since 3.17.0 +---@field editRange? lsp.Range|anonym3 +---A default insert text format. +--- +---@since 3.17.0 +---@field insertTextFormat? lsp.InsertTextFormat +---A default insert text mode. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---A default data value. +--- +---@since 3.17.0 +---@field data? lsp.LSPAny + +---@class anonym4 +---Human readable description of why the code action is currently disabled. +--- +---This is displayed in the code actions UI. +---@field reason string + +---@class anonym5 +---@field uri lsp.DocumentUri + +---@class anonym6 + +---@class anonym7 +---The server supports deltas for full documents. +---@field delta? boolean + +---@class anonym9 +---The change to the cell array. +---@field array lsp.NotebookCellArrayChange +---Additional opened cell text documents. +---@field didOpen? lsp.TextDocumentItem[] +---Additional closed cell text documents. +---@field didClose? lsp.TextDocumentIdentifier[] + +---@class anonym10 +---@field document lsp.VersionedTextDocumentIdentifier +---@field changes lsp.TextDocumentContentChangeEvent[] + +---@class anonym8 +---Changes to the cell structure to add or +---remove cells. +---@field structure? anonym9 +---Changes to notebook cells properties like its +---kind, execution summary or metadata. +---@field data? lsp.NotebookCell[] +---Changes to the text content of notebook cells. +---@field textContent? anonym10[] + +---@class anonym11 +---The name of the client as defined by the client. +---@field name string +---The client's version as defined by the client. +---@field version? string + +---@class anonym12 +---The server supports workspace folder. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFoldersServerCapabilities +---The server is interested in notifications/requests for operations on files. +--- +---@since 3.16.0 +---@field fileOperations? lsp.FileOperationOptions + +---@class anonym13 +---The server has support for completion item label +---details (see also `CompletionItemLabelDetails`) when +---receiving a completion item in a resolve call. +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym15 +---@field language string + +---@class anonym14 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells? anonym15[] + +---@class anonym17 +---@field language string + +---@class anonym16 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook? string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells anonym17[] + +---@class anonym18 +---The client will actively cancel the request. +---@field cancel boolean +---The list of requests for which the client +---will retry the request if it receives a +---response with error code `ContentModified` +---@field retryOnContentModified string[] + +---@class anonym19 +---Whether the client groups edits with equal labels into tree nodes, +---for instance all edits labelled with "Changes in Strings" would +---be a tree node. +---@field groupsOnLabel? boolean + +---@class anonym20 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym21 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym22 +---The properties that a client can resolve lazily. Usually +---`location.range` +---@field properties string[] + +---@class anonym24 +---The tags supported by the client. +---@field valueSet lsp.CompletionItemTag[] + +---@class anonym25 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym26 +---@field valueSet lsp.InsertTextMode[] + +---@class anonym23 +---Client supports snippets as insert text. +--- +---A snippet can define tab stops and placeholders with `$1`, `$2` +---and `${3:foo}`. `$0` defines the final tab stop, it defaults to +---the end of the snippet. Placeholders with equal identifiers are linked, +---that is typing in one will update others too. +---@field snippetSupport? boolean +---Client supports commit characters on a completion item. +---@field commitCharactersSupport? boolean +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client supports the deprecated property on a completion item. +---@field deprecatedSupport? boolean +---Client supports the preselect property on a completion item. +---@field preselectSupport? boolean +---Client supports the tag property on a completion item. Clients supporting +---tags have to handle unknown tags gracefully. Clients especially need to +---preserve unknown tags when sending a completion item back to the server in +---a resolve call. +--- +---@since 3.15.0 +---@field tagSupport? anonym24 +---Client support insert replace edit to control different behavior if a +---completion item is inserted in the text or should replace text. +--- +---@since 3.16.0 +---@field insertReplaceSupport? boolean +---Indicates which properties a client can resolve lazily on a completion +---item. Before version 3.16.0 only the predefined properties `documentation` +---and `details` could be resolved lazily. +--- +---@since 3.16.0 +---@field resolveSupport? anonym25 +---The client supports the `insertTextMode` property on +---a completion item to override the whitespace handling mode +---as defined by the client (see `insertTextMode`). +--- +---@since 3.16.0 +---@field insertTextModeSupport? anonym26 +---The client has support for completion item label +---details (see also `CompletionItemLabelDetails`). +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym27 +---The completion item kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the completion items kinds from `Text` to `Reference` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.CompletionItemKind[] + +---@class anonym28 +---The client supports the following itemDefaults on +---a completion list. +--- +---The value lists the supported property names of the +---`CompletionList.itemDefaults` object. If omitted +---no properties are supported. +--- +---@since 3.17.0 +---@field itemDefaults? string[] + +---@class anonym30 +---The client supports processing label offsets instead of a +---simple label string. +--- +---@since 3.14.0 +---@field labelOffsetSupport? boolean + +---@class anonym29 +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client capabilities specific to parameter information. +---@field parameterInformation? anonym30 +---The client supports the `activeParameter` property on `SignatureInformation` +---literal. +--- +---@since 3.16.0 +---@field activeParameterSupport? boolean + +---@class anonym31 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym32 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym34 +---The code action kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet lsp.CodeActionKind[] + +---@class anonym33 +---The code action kind is support with the following value +---set. +---@field codeActionKind anonym34 + +---@class anonym35 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym36 +---The folding range kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet? lsp.FoldingRangeKind[] + +---@class anonym37 +---If set, the client signals that it supports setting collapsedText on +---folding ranges to display custom labels instead of the default text. +--- +---@since 3.17.0 +---@field collapsedText? boolean + +---@class anonym38 +---The tags supported by the client. +---@field valueSet lsp.DiagnosticTag[] + +---@class anonym40 + +---@class anonym41 +---The client will send the `textDocument/semanticTokens/full/delta` request if +---the server provides a corresponding handler. +---@field delta? boolean + +---@class anonym39 +---The client will send the `textDocument/semanticTokens/range` request if +---the server provides a corresponding handler. +---@field range? boolean|anonym40 +---The client will send the `textDocument/semanticTokens/full` request if +---the server provides a corresponding handler. +---@field full? boolean|anonym41 + +---@class anonym42 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym43 +---Whether the client supports additional attributes which +---are preserved and send back to the server in the +---request's response. +---@field additionalPropertiesSupport? boolean + +---@class anonym44 +---@field range lsp.Range +---@field placeholder string + +---@class anonym45 +---@field defaultBehavior boolean + +---@class anonym46 +---The range of the document that changed. +---@field range lsp.Range +---The optional length of the range that got replaced. +--- +---@deprecated use range instead. +---@field rangeLength? uinteger +---The new text for the provided range. +---@field text string + +---@class anonym47 +---The new text of the whole document. +---@field text string + +---@class anonym48 +---@field language string +---@field value string + +---@class anonym49 +---A language id, like `typescript`. +---@field language string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym50 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym51 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern string + +---@class anonym52 +---The type of the enclosing notebook. +---@field notebookType string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern? string + +---@class anonym53 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern. +---@field pattern? string + +---@class anonym54 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern string -- cgit From 4ecc71f6fc7377403ed91ae5bc32992a5d08f678 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Wed, 7 Jun 2023 13:39:41 +0100 Subject: fix(lsp): reduce diagnostics and add more types (#23948) --- runtime/lua/vim/lsp/protocol.lua | 1 + 1 file changed, 1 insertion(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 7558b5c6ba..172d43e483 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -632,6 +632,7 @@ export interface WorkspaceClientCapabilities { --- Gets a new ClientCapabilities object describing the LSP client --- capabilities. +--- @return lsp.ClientCapabilities function protocol.make_client_capabilities() return { general = { -- cgit From c0952e62fd0ee16a3275bb69e0de04c836b39015 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Wed, 7 Jun 2023 13:52:23 +0100 Subject: feat(lua): add `vim.system()` feat(lua): add vim.system() Problem: Handling system commands in Lua is tedious and error-prone: - vim.fn.jobstart() is vimscript and comes with all limitations attached to typval. - vim.loop.spawn is too low level Solution: Add vim.system(). Partly inspired by Python's subprocess module Does not expose any libuv objects. --- runtime/lua/vim/lsp/rpc.lua | 124 +++++++++++++++++--------------------------- 1 file changed, 47 insertions(+), 77 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 5f48effebf..64bc732bdf 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -14,32 +14,6 @@ local function is_dir(filename) return stat and stat.type == 'directory' or false end ----@private ---- Merges current process env with the given env and returns the result as ---- a list of "k=v" strings. ---- ----
---- Example:
----
----  in:    { PRODUCTION="false", PATH="/usr/bin/", PORT=123, HOST="0.0.0.0", }
----  out:   { "PRODUCTION=false", "PATH=/usr/bin/", "PORT=123", "HOST=0.0.0.0", }
---- 
----@param env (table) table of environment variable assignments ----@returns (table) list of `"k=v"` strings -local function env_merge(env) - if env == nil then - return env - end - -- Merge. - env = vim.tbl_extend('force', vim.fn.environ(), env) - local final_env = {} - for k, v in pairs(env) do - assert(type(k) == 'string', 'env must be a dict') - table.insert(final_env, k .. '=' .. tostring(v)) - end - return final_env -end - ---@private --- Embeds the given string into a table and correctly computes `Content-Length`. --- @@ -658,89 +632,85 @@ end --- - `is_closing()` returns a boolean indicating if the RPC is closing. --- - `terminate()` terminates the RPC client. local function start(cmd, cmd_args, dispatchers, extra_spawn_params) - local _ = log.info() - and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) + if log.info() then + log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) + end + validate({ cmd = { cmd, 's' }, cmd_args = { cmd_args, 't' }, dispatchers = { dispatchers, 't', true }, }) - if extra_spawn_params and extra_spawn_params.cwd then + extra_spawn_params = extra_spawn_params or {} + + if extra_spawn_params.cwd then assert(is_dir(extra_spawn_params.cwd), 'cwd must be a directory') end dispatchers = merge_dispatchers(dispatchers) - local stdin = uv.new_pipe(false) - local stdout = uv.new_pipe(false) - local stderr = uv.new_pipe(false) - local handle, pid + + local sysobj ---@type SystemObj local client = new_client(dispatchers, { write = function(msg) - stdin:write(msg) + sysobj:write(msg) end, is_closing = function() - return handle == nil or handle:is_closing() + return sysobj == nil or sysobj:is_closing() end, terminate = function() - if handle then - handle:kill(15) - end + sysobj:kill(15) end, }) - ---@private - --- Callback for |vim.uv.spawn()| Closes all streams and runs the `on_exit` dispatcher. - ---@param code (integer) Exit code - ---@param signal (integer) Signal that was used to terminate (if any) - local function onexit(code, signal) - stdin:close() - stdout:close() - stderr:close() - handle:close() - dispatchers.on_exit(code, signal) + local handle_body = function(body) + client:handle_body(body) end - local spawn_params = { - args = cmd_args, - stdio = { stdin, stdout, stderr }, - detached = not is_win, - } - if extra_spawn_params then - spawn_params.cwd = extra_spawn_params.cwd - spawn_params.env = env_merge(extra_spawn_params.env) - if extra_spawn_params.detached ~= nil then - spawn_params.detached = extra_spawn_params.detached + + local stdout_handler = create_read_loop(handle_body, nil, function(err) + client:on_error(client_errors.READ_ERROR, err) + end) + + local stderr_handler = function(_, chunk) + if chunk and log.error() then + log.error('rpc', cmd, 'stderr', chunk) end end - handle, pid = uv.spawn(cmd, spawn_params, onexit) - if handle == nil then - stdin:close() - stdout:close() - stderr:close() + + local detached = not is_win + if extra_spawn_params.detached ~= nil then + detached = extra_spawn_params.detached + end + + local cmd1 = { cmd } + vim.list_extend(cmd1, cmd_args) + + local ok, sysobj_or_err = pcall(vim.system, cmd1, { + stdin = true, + stdout = stdout_handler, + stderr = stderr_handler, + cwd = extra_spawn_params.cwd, + env = extra_spawn_params.env, + detach = detached, + }, function(obj) + dispatchers.on_exit(obj.code, obj.signal) + end) + + if not ok then + local err = sysobj_or_err --[[@as string]] local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) - if string.match(pid, 'ENOENT') then + if string.match(err, 'ENOENT') then msg = msg .. '. The language server is either not installed, missing from PATH, or not executable.' else - msg = msg .. string.format(' with error message: %s', pid) + msg = msg .. string.format(' with error message: %s', err) end vim.notify(msg, vim.log.levels.WARN) return end - stderr:read_start(function(_, chunk) - if chunk then - local _ = log.error() and log.error('rpc', cmd, 'stderr', chunk) - end - end) - - local handle_body = function(body) - client:handle_body(body) - end - stdout:read_start(create_read_loop(handle_body, nil, function(err) - client:on_error(client_errors.READ_ERROR, err) - end)) + sysobj = sysobj_or_err --[[@as SystemObj]] return public_client(client) end -- cgit From e5e0bda41b640d324350c5147b956e37e9f8b32c Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Fri, 9 Jun 2023 11:32:43 +0200 Subject: feat(lsp)!: add vim.lsp.status, client.progress and promote LspProgressUpdate (#23958) `client.messages` could grow unbounded because the default handler only added new messages, never removing them. A user either had to consume the messages by calling `vim.lsp.util.get_progress_messages` or by manually removing them from `client.messages.progress`. If they didn't do that, using LSP effectively leaked memory. To fix this, this deprecates the `messages` property and instead adds a `progress` ring buffer that only keeps at most 50 messages. In addition it deprecates `vim.lsp.util.get_progress_messages` in favour of a new `vim.lsp.status()` and also promotes the `LspProgressUpdate` user autocmd to a regular autocmd to allow users to pattern match on the progress kind. Also closes https://github.com/neovim/neovim/pull/20327 --- runtime/lua/vim/lsp/handlers.lua | 75 +++++++++++++++++----------------------- runtime/lua/vim/lsp/types.lua | 8 ++++- runtime/lua/vim/lsp/util.lua | 29 ++++++++++++++++ 3 files changed, 68 insertions(+), 44 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 5346160871..19338ae8f0 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -9,7 +9,7 @@ local M = {} ---@private --- Writes to error buffer. ----@param ... (table of strings) Will be concatenated before being written +---@param ... string Will be concatenated before being written local function err_message(...) vim.notify(table.concat(vim.tbl_flatten({ ... })), vim.log.levels.ERROR) api.nvim_command('redraw') @@ -20,63 +20,52 @@ M['workspace/executeCommand'] = function(_, _, _, _) -- Error handling is done implicitly by wrapping all handlers; see end of this file end ----@private -local function progress_handler(_, result, ctx, _) - local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress +---@param result lsp.ProgressParams +---@param ctx lsp.HandlerContext +M['$/progress'] = function(_, result, ctx) + local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then - err_message('LSP[', client_name, '] client has shut down during progress update') + err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') return vim.NIL end - local val = result.value -- unspecified yet - local token = result.token -- string or number + local kind = nil + local value = result.value - if type(val) ~= 'table' then - val = { content = val } - end - if val.kind then - if val.kind == 'begin' then - client.messages.progress[token] = { - title = val.title, - cancellable = val.cancellable, - message = val.message, - percentage = val.percentage, - } - elseif val.kind == 'report' then - client.messages.progress[token].cancellable = val.cancellable - client.messages.progress[token].message = val.message - client.messages.progress[token].percentage = val.percentage - elseif val.kind == 'end' then - if client.messages.progress[token] == nil then - err_message('LSP[', client_name, '] received `end` message with no corresponding `begin`') - else - client.messages.progress[token].message = val.message - client.messages.progress[token].done = true + if type(value) == 'table' then + kind = value.kind + -- Carry over title of `begin` messages to `report` and `end` messages + -- So that consumers always have it available, even if they consume a + -- subset of the full sequence + if kind == 'begin' then + client.progress.pending[result.token] = value.title + else + value.title = client.progress.pending[result.token] + if kind == 'end' then + client.progress.pending[result.token] = nil end end - else - client.messages.progress[token] = val - client.messages.progress[token].done = true end - api.nvim_exec_autocmds('User', { pattern = 'LspProgressUpdate', modeline = false }) -end + client.progress:push(result) ---see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress -M['$/progress'] = progress_handler + api.nvim_exec_autocmds('LspProgress', { + pattern = kind, + modeline = false, + data = { client_id = ctx.client_id, result = result }, + }) +end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create +---@param result lsp.WorkDoneProgressCreateParams +---@param ctx lsp.HandlerContext M['window/workDoneProgress/create'] = function(_, result, ctx) - local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) - local token = result.token -- string or number - local client_name = client and client.name or string.format('id=%d', client_id) + local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then - err_message('LSP[', client_name, '] client has shut down while creating progress report') + err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') return vim.NIL end - client.messages.progress[token] = {} + client.progress:push(result) return vim.NIL end diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index e77e1fb63a..ef85a0d10f 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -1,6 +1,12 @@ ---@meta ----@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: table, config: table|nil) +---@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil) + +---@class lsp.HandlerContext +---@field method string +---@field client_id integer +---@field bufnr integer +---@field params any ---@class lsp.ResponseError ---@field code integer diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index e36014d07d..538e48c805 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -353,11 +353,40 @@ end --- Process and return progress reports from lsp server ---@private +---@deprecated Use vim.lsp.status() or access client.progress directly function M.get_progress_messages() + vim.deprecate('vim.lsp.util.get_progress_messages', 'vim.lsp.status', '0.11.0') local new_messages = {} local progress_remove = {} for _, client in ipairs(vim.lsp.get_active_clients()) do + local groups = {} + for progress in client.progress do + local value = progress.value + if type(value) == 'table' and value.kind then + local group = groups[progress.token] + if not group then + group = { + done = false, + progress = true, + title = 'empty title', + } + groups[progress.token] = group + end + group.title = value.title or group.title + group.cancellable = value.cancellable or group.cancellable + if value.kind == 'end' then + group.done = true + end + group.message = value.message or group.message + group.percentage = value.percentage or group.percentage + end + end + + for _, group in pairs(groups) do + table.insert(new_messages, group) + end + local messages = client.messages local data = messages for token, ctx in pairs(data.progress) do -- cgit From 643546b82b4bc0c29ca869f81af868a019723d83 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Sun, 11 Jun 2023 15:23:37 +0530 Subject: feat(lsp): add handlers for inlay hints (#23736) initial support; public API left for a follow-up PR --- runtime/lua/vim/lsp/_inlay_hint.lua | 217 ++++++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/handlers.lua | 26 +++++ runtime/lua/vim/lsp/protocol.lua | 9 ++ runtime/lua/vim/lsp/types.lua | 25 +++++ 4 files changed, 277 insertions(+) create mode 100644 runtime/lua/vim/lsp/_inlay_hint.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua new file mode 100644 index 0000000000..aa6ec9aca8 --- /dev/null +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -0,0 +1,217 @@ +local util = require('vim.lsp.util') +local log = require('vim.lsp.log') +local api = vim.api +local M = {} + +---@class lsp._inlay_hint.bufstate +---@field version integer +---@field client_hint table> client_id -> (lnum -> hints) + +---@type table +local hint_cache_by_buf = setmetatable({}, { + __index = function(t, b) + local key = b > 0 and b or api.nvim_get_current_buf() + return rawget(t, key) + end, +}) + +local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') + +M.__explicit_buffers = {} + +--- |lsp-handler| for the method `textDocument/inlayHint` +--- Store hints for a specific buffer and client +--- Resolves unresolved hints +---@private +function M.on_inlayhint(err, result, ctx, _) + if err then + local _ = log.error() and log.error('inlayhint', err) + return + end + local bufnr = ctx.bufnr + if util.buf_versions[bufnr] ~= ctx.version then + return + end + local client_id = ctx.client_id + if not result then + return + end + local bufstate = hint_cache_by_buf[bufnr] + if not bufstate then + bufstate = { + client_hint = vim.defaulttable(), + version = ctx.version, + } + hint_cache_by_buf[bufnr] = bufstate + api.nvim_buf_attach(bufnr, false, { + on_detach = function(_, b) + api.nvim_buf_clear_namespace(b, namespace, 0, -1) + hint_cache_by_buf[b] = nil + end, + on_reload = function(_, b) + api.nvim_buf_clear_namespace(b, namespace, 0, -1) + hint_cache_by_buf[b] = nil + end, + }) + end + local hints_by_client = bufstate.client_hint + local client = vim.lsp.get_client_by_id(client_id) + + local new_hints_by_lnum = vim.defaulttable() + local num_unprocessed = #result + if num_unprocessed == 0 then + hints_by_client[client_id] = {} + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) + return + end + + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) + ---@private + local function pos_to_byte(position) + local col = position.character + if col > 0 then + local line = lines[position.line + 1] or '' + local ok, convert_result + ok, convert_result = pcall(util._str_byteindex_enc, line, col, client.offset_encoding) + if ok then + return convert_result + end + return math.min(#line, col) + end + return col + end + + for _, hint in ipairs(result) do + local lnum = hint.position.line + hint.position.character = pos_to_byte(hint.position) + table.insert(new_hints_by_lnum[lnum], hint) + end + + hints_by_client[client_id] = new_hints_by_lnum + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +---@private +local function resolve_bufnr(bufnr) + return bufnr == 0 and api.nvim_get_current_buf() or bufnr +end + +--- Refresh inlay hints for a buffer +--- +--- It is recommended to trigger this using an autocmd or via keymap. +---@param opts (nil|table) Optional arguments +--- - bufnr (integer, default: 0): Buffer whose hints to refresh +--- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer +--- +--- Example: +---
vim
+---   autocmd BufEnter,InsertLeave,BufWritePost  lua vim.lsp._inlay_hint.refresh()
+--- 
+--- +---@private +function M.refresh(opts) + opts = opts or {} + local bufnr = opts.bufnr or 0 + local only_visible = opts.only_visible or false + bufnr = resolve_bufnr(bufnr) + M.__explicit_buffers[bufnr] = true + local buffer_windows = {} + for _, winid in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(winid) == bufnr then + table.insert(buffer_windows, winid) + end + end + for _, window in ipairs(buffer_windows) do + local first = vim.fn.line('w0', window) + local last = vim.fn.line('w$', window) + local params = { + textDocument = util.make_text_document_params(bufnr), + range = { + start = { line = first - 1, character = 0 }, + ['end'] = { line = last, character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) + end + if not only_visible then + local params = { + textDocument = util.make_text_document_params(bufnr), + range = { + start = { line = 0, character = 0 }, + ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) + end +end + +--- Clear inlay hints +--- +---@param client_id integer|nil filter by client_id. All clients if nil +---@param bufnr integer|nil filter by buffer. All buffers if nil +---@private +function M.clear(client_id, bufnr) + local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(hint_cache_by_buf) + for _, iter_bufnr in ipairs(buffers) do + M.__explicit_buffers[iter_bufnr] = false + local bufstate = hint_cache_by_buf[iter_bufnr] + local client_lens = (bufstate or {}).client_hint or {} + local client_ids = client_id and { client_id } or vim.tbl_keys(client_lens) + for _, iter_client_id in ipairs(client_ids) do + if bufstate then + bufstate.client_hint[iter_client_id] = {} + end + end + api.nvim_buf_clear_namespace(iter_bufnr, namespace, 0, -1) + end + vim.cmd('redraw!') +end + +api.nvim_set_decoration_provider(namespace, { + on_win = function(_, _, bufnr, topline, botline) + local bufstate = hint_cache_by_buf[bufnr] + if not bufstate then + return + end + + if bufstate.version ~= util.buf_versions[bufnr] then + return + end + local hints_by_client = bufstate.client_hint + api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) + + for lnum = topline, botline do + for _, hints_by_lnum in pairs(hints_by_client) do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local text = '' + if type(hint.label) == 'string' then + text = hint.label + else + for _, part in ipairs(hint.label) do + text = text .. part.value + end + end + if hint.paddingLeft then + text = ' ' .. text + end + if hint.paddingRight then + text = text .. ' ' + end + api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { + virt_text_pos = 'inline', + ephemeral = false, + virt_text = { + { text, 'LspInlayHint' }, + }, + hl_mode = 'combine', + }) + end + end + end + end, +}) + +return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 19338ae8f0..44a9a58aca 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -219,6 +219,10 @@ M['textDocument/codeLens'] = function(...) return require('vim.lsp.codelens').on_codelens(...) end +M['textDocument/inlayHint'] = function(...) + return require('vim.lsp._inlay_hint').on_inlayhint(...) +end + --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references M['textDocument/references'] = function(_, result, ctx, config) if not result or vim.tbl_isempty(result) then @@ -612,6 +616,28 @@ M['window/showDocument'] = function(_, result, ctx, _) return { success = success or false } end +---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh +M['workspace/inlayHint/refresh'] = function(err, _, ctx) + local inlay_hint = require('vim.lsp._inlay_hint') + if not inlay_hint.__explicit_buffers[ctx.bufnr] then + return vim.NIL + end + if err then + return vim.NIL + end + + for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do + for _, winid in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(winid) == bufnr then + inlay_hint.refresh({ bufnr = bufnr }) + break + end + end + end + + return vim.NIL +end + -- Add boilerplate error validation and logging for all of these. for k, fn in pairs(M) do M[k] = function(err, result, ctx, config) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 172d43e483..b3a7903420 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -641,6 +641,12 @@ function protocol.make_client_capabilities() }, }, textDocument = { + inlayHint = { + dynamicRegistration = false, + resolveSupport = { + properties = {}, + }, + }, semanticTokens = { dynamicRegistration = false, tokenTypes = { @@ -853,6 +859,9 @@ function protocol.make_client_capabilities() dynamicRegistration = true, relativePatternSupport = true, }, + inlayHint = { + refreshSupport = true, + }, }, experimental = nil, window = { diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index ef85a0d10f..108aeeb922 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -69,3 +69,28 @@ --- @field method string --- @alias lsp.UnregistrationParams {unregisterations: lsp.Unregistration[]} + +---@class lsp.Location +---@field uri string +---@field range lsp.Range + +---@class lsp.MarkupContent +---@field kind string +---@field value string + +---@class lsp.InlayHintLabelPart +---@field value string +---@field tooltip? string | lsp.MarkupContent +---@field location? lsp.Location + +---@class lsp.TextEdit +---@field range lsp.Range +---@field newText string + +---@class lsp.InlayHint +---@field position lsp.Position +---@field label string | lsp.InlayHintLabelPart[] +---@field kind? integer +---@field textEdits? lsp.TextEdit[] +---@field paddingLeft? boolean +---@field paddingRight? boolean -- cgit From bc67bbe4469b777a958f5ad515dec777777e9f2d Mon Sep 17 00:00:00 2001 From: Rohit Sukumaran Date: Tue, 13 Jun 2023 20:47:35 +0530 Subject: fix(codelens): add buffer and line checks before displaying codelens (#23887) Co-authored-by: Rohit Sukumaran --- runtime/lua/vim/lsp/codelens.lua | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index ea8c52c334..e26bdcc6d4 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -136,6 +136,10 @@ end ---@param bufnr integer ---@param client_id integer function M.display(lenses, bufnr, client_id) + if not api.nvim_buf_is_loaded(bufnr) then + return + end + local ns = namespaces[client_id] if not lenses or not next(lenses) then api.nvim_buf_clear_namespace(bufnr, ns, 0, -1) @@ -181,6 +185,10 @@ end ---@param bufnr integer ---@param client_id integer function M.save(lenses, bufnr, client_id) + if not api.nvim_buf_is_loaded(bufnr) then + return + end + local lenses_by_client = lens_cache_by_buf[bufnr] if not lenses_by_client then lenses_by_client = {} @@ -221,19 +229,24 @@ local function resolve_lenses(lenses, bufnr, client_id, callback) countdown() else client.request('codeLens/resolve', lens, function(_, result) - if result and result.command then + if api.nvim_buf_is_loaded(bufnr) and result and result.command then lens.command = result.command -- Eager display to have some sort of incremental feedback -- Once all lenses got resolved there will be a full redraw for all lenses -- So that multiple lens per line are properly displayed - api.nvim_buf_set_extmark( - bufnr, - ns, - lens.range.start.line, - 0, - { virt_text = { { lens.command.title, 'LspCodeLens' } }, hl_mode = 'combine' } - ) + + local num_lines = api.nvim_buf_line_count(bufnr) + if lens.range.start.line <= num_lines then + api.nvim_buf_set_extmark( + bufnr, + ns, + lens.range.start.line, + 0, + { virt_text = { { lens.command.title, 'LspCodeLens' } }, hl_mode = 'combine' } + ) + end end + countdown() end, bufnr) end -- cgit From 79a5b89d66db74560e751561542064674e980146 Mon Sep 17 00:00:00 2001 From: Jon Huhn Date: Wed, 14 Jun 2023 05:40:11 -0500 Subject: perf(lsp): reduce polling handles for workspace/didChangeWatchedFiles (#23500) Co-authored-by: Lewis Russell --- runtime/lua/vim/lsp/_watchfiles.lua | 52 +++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 17 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 14e5dc6cf8..87938fe4d5 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -1,7 +1,7 @@ local bit = require('bit') -local lpeg = require('lpeg') local watch = require('vim._watch') local protocol = require('vim.lsp.protocol') +local lpeg = vim.lpeg local M = {} @@ -107,6 +107,13 @@ local to_lsp_change_type = { [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted, } +--- Default excludes the same as VSCode's `files.watcherExclude` setting. +--- https://github.com/microsoft/vscode/blob/eef30e7165e19b33daa1e15e92fa34ff4a5df0d3/src/vs/workbench/contrib/files/browser/files.contribution.ts#L261 +---@type Lpeg pattern +M._poll_exclude_pattern = parse('**/.git/{objects,subtree-cache}/**') + + parse('**/node_modules/*/**') + + parse('**/.hg/store/**') + --- Registers the workspace/didChangeWatchedFiles capability dynamically. --- ---@param reg table LSP Registration object. @@ -122,10 +129,10 @@ function M.register(reg, ctx) then return end - local watch_regs = {} + local watch_regs = {} --- @type table for _, w in ipairs(reg.registerOptions.watchers) do local relative_pattern = false - local glob_patterns = {} + local glob_patterns = {} --- @type {baseUri:string, pattern: string}[] if type(w.globPattern) == 'string' then for _, folder in ipairs(client.workspace_folders) do table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) @@ -135,7 +142,7 @@ function M.register(reg, ctx) table.insert(glob_patterns, w.globPattern) end for _, glob_pattern in ipairs(glob_patterns) do - local base_dir = nil + local base_dir = nil ---@type string? if type(glob_pattern.baseUri) == 'string' then base_dir = glob_pattern.baseUri elseif type(glob_pattern.baseUri) == 'table' then @@ -144,6 +151,7 @@ function M.register(reg, ctx) assert(base_dir, "couldn't identify root of watch") base_dir = vim.uri_to_fname(base_dir) + ---@type integer local kind = w.kind or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete @@ -153,8 +161,8 @@ function M.register(reg, ctx) pattern = lpeg.P(base_dir .. '/') * pattern end - table.insert(watch_regs, { - base_dir = base_dir, + watch_regs[base_dir] = watch_regs[base_dir] or {} + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind, }) @@ -163,12 +171,12 @@ function M.register(reg, ctx) local callback = function(base_dir) return function(fullpath, change_type) - for _, w in ipairs(watch_regs) do + for _, w in ipairs(watch_regs[base_dir]) do change_type = to_lsp_change_type[change_type] -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) local kind_mask = bit.lshift(1, change_type - 1) local change_type_match = bit.band(w.kind, kind_mask) == kind_mask - if base_dir == w.base_dir and M._match(w.pattern, fullpath) and change_type_match then + if M._match(w.pattern, fullpath) and change_type_match then local change = { uri = vim.uri_from_fname(fullpath), type = change_type, @@ -198,15 +206,25 @@ function M.register(reg, ctx) end end - local watching = {} - for _, w in ipairs(watch_regs) do - if not watching[w.base_dir] then - watching[w.base_dir] = true - table.insert( - cancels[client_id][reg.id], - M._watchfunc(w.base_dir, { uvflags = { recursive = true } }, callback(w.base_dir)) - ) - end + for base_dir, watches in pairs(watch_regs) do + local include_pattern = vim.iter(watches):fold(lpeg.P(false), function(acc, w) + return acc + w.pattern + end) + + table.insert( + cancels[client_id][reg.id], + M._watchfunc(base_dir, { + uvflags = { + recursive = true, + }, + -- include_pattern will ensure the pattern from *any* watcher definition for the + -- base_dir matches. This first pass prevents polling for changes to files that + -- will never be sent to the LSP server. A second pass in the callback is still necessary to + -- match a *particular* pattern+kind pair. + include_pattern = include_pattern, + exclude_pattern = M._poll_exclude_pattern, + }, callback(base_dir)) + ) end end -- cgit From c07dceba335c56c9a356395ad0d1e5a14d416752 Mon Sep 17 00:00:00 2001 From: Jonas Strittmatter <40792180+smjonas@users.noreply.github.com> Date: Sat, 17 Jun 2023 08:01:31 +0200 Subject: fix(lsp): allow Lua pattern chars in code action filter (#24041) Previously, filtering code actions with the "only" option failed if the code action kind contained special Lua pattern chars such as "-" (e.g. the ocaml language server supports a "type-annotate" code action). Solution: use string comparison instead of string.find --- runtime/lua/vim/lsp/buf.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bb3ca0e6d6..e0034cf86e 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -608,9 +608,9 @@ local function on_code_action_results(results, ctx, options) end local found = false for _, o in ipairs(options.context.only) do - -- action kinds are hierarchical with . as a separator: when requesting only - -- 'quickfix' this filter allows both 'quickfix' and 'quickfix.foo', for example - if a.kind:find('^' .. o .. '$') or a.kind:find('^' .. o .. '%.') then + -- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate' + -- this filter allows both 'type-annotate' and 'type-annotate.foo', for example + if a.kind == o or vim.startswith(a.kind, o .. '.') then found = true break end -- cgit From ca5de9306c00d07cce1daef1f0038c937098bc66 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Tue, 20 Jun 2023 11:36:54 +0530 Subject: feat(lsp): inlay hints #23984 Add automatic refresh and a public interface on top of #23736 * add on_reload, on_detach handlers in `enable()` buf_attach, and LspDetach autocommand in case of manual detach * unify `__buffers` and `hint_cache_by_buf` * use callback bufnr in `on_lines` callback, bufstate: remove __index override * move user-facing functions into vim.lsp.buf, unify enable/disable/toggle Closes #18086 --- runtime/lua/vim/lsp/_inlay_hint.lua | 164 +++++++++++++++++++++++++----------- runtime/lua/vim/lsp/buf.lua | 15 ++++ runtime/lua/vim/lsp/handlers.lua | 3 - 3 files changed, 131 insertions(+), 51 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index aa6ec9aca8..70d332a1ac 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -6,22 +6,30 @@ local M = {} ---@class lsp._inlay_hint.bufstate ---@field version integer ---@field client_hint table> client_id -> (lnum -> hints) +---@field enabled boolean Whether inlay hints are enabled for the buffer +---@field timer uv.uv_timer_t? Debounce timer associated with the buffer ---@type table -local hint_cache_by_buf = setmetatable({}, { - __index = function(t, b) - local key = b > 0 and b or api.nvim_get_current_buf() - return rawget(t, key) - end, -}) +local bufstates = {} local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') +local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) -M.__explicit_buffers = {} +--- Reset the request debounce timer of a buffer +---@private +local function reset_timer(reset_bufnr) + local timer = bufstates[reset_bufnr].timer + if timer then + bufstates[reset_bufnr].timer = nil + if not timer:is_closing() then + timer:stop() + timer:close() + end + end +end --- |lsp-handler| for the method `textDocument/inlayHint` --- Store hints for a specific buffer and client ---- Resolves unresolved hints ---@private function M.on_inlayhint(err, result, ctx, _) if err then @@ -36,21 +44,20 @@ function M.on_inlayhint(err, result, ctx, _) if not result then return end - local bufstate = hint_cache_by_buf[bufnr] - if not bufstate then - bufstate = { - client_hint = vim.defaulttable(), - version = ctx.version, - } - hint_cache_by_buf[bufnr] = bufstate + local bufstate = bufstates[bufnr] + if not (bufstate.client_hint and bufstate.version) then + bufstate.client_hint = vim.defaulttable() + bufstate.version = ctx.version api.nvim_buf_attach(bufnr, false, { - on_detach = function(_, b) - api.nvim_buf_clear_namespace(b, namespace, 0, -1) - hint_cache_by_buf[b] = nil + on_detach = function(_, cb_bufnr) + api.nvim_buf_clear_namespace(cb_bufnr, namespace, 0, -1) + bufstates[cb_bufnr].version = nil + bufstates[cb_bufnr].client_hint = nil end, - on_reload = function(_, b) - api.nvim_buf_clear_namespace(b, namespace, 0, -1) - hint_cache_by_buf[b] = nil + on_reload = function(_, cb_bufnr) + api.nvim_buf_clear_namespace(cb_bufnr, namespace, 0, -1) + bufstates[cb_bufnr].version = nil + bufstates[cb_bufnr].client_hint = nil end, }) end @@ -95,28 +102,24 @@ end ---@private local function resolve_bufnr(bufnr) - return bufnr == 0 and api.nvim_get_current_buf() or bufnr + return bufnr > 0 and bufnr or api.nvim_get_current_buf() end --- Refresh inlay hints for a buffer --- ---- It is recommended to trigger this using an autocmd or via keymap. ---@param opts (nil|table) Optional arguments --- - bufnr (integer, default: 0): Buffer whose hints to refresh --- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer --- ---- Example: ----
vim
----   autocmd BufEnter,InsertLeave,BufWritePost  lua vim.lsp._inlay_hint.refresh()
---- 
---- ---@private function M.refresh(opts) opts = opts or {} - local bufnr = opts.bufnr or 0 + local bufnr = resolve_bufnr(opts.bufnr or 0) + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.enabled) then + return + end local only_visible = opts.only_visible or false - bufnr = resolve_bufnr(bufnr) - M.__explicit_buffers[bufnr] = true local buffer_windows = {} for _, winid in ipairs(api.nvim_list_wins()) do if api.nvim_win_get_buf(winid) == bufnr then @@ -148,30 +151,95 @@ function M.refresh(opts) end --- Clear inlay hints ---- ----@param client_id integer|nil filter by client_id. All clients if nil ----@param bufnr integer|nil filter by buffer. All buffers if nil +---@param bufnr (integer) Buffer handle, or 0 for current ---@private -function M.clear(client_id, bufnr) - local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(hint_cache_by_buf) - for _, iter_bufnr in ipairs(buffers) do - M.__explicit_buffers[iter_bufnr] = false - local bufstate = hint_cache_by_buf[iter_bufnr] - local client_lens = (bufstate or {}).client_hint or {} - local client_ids = client_id and { client_id } or vim.tbl_keys(client_lens) - for _, iter_client_id in ipairs(client_ids) do - if bufstate then - bufstate.client_hint[iter_client_id] = {} - end +local function clear(bufnr) + bufnr = resolve_bufnr(bufnr) + reset_timer(bufnr) + local bufstate = bufstates[bufnr] + local client_lens = (bufstate or {}).client_hint or {} + local client_ids = vim.tbl_keys(client_lens) + for _, iter_client_id in ipairs(client_ids) do + if bufstate then + bufstate.client_hint[iter_client_id] = {} end - api.nvim_buf_clear_namespace(iter_bufnr, namespace, 0, -1) end - vim.cmd('redraw!') + api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +---@private +local function make_request(request_bufnr) + reset_timer(request_bufnr) + M.refresh({ bufnr = request_bufnr }) +end + +--- Enable inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +function M.enable(bufnr) + bufnr = resolve_bufnr(bufnr) + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.enabled) then + bufstates[bufnr] = { enabled = true, timer = nil } + M.refresh({ bufnr = bufnr }) + api.nvim_buf_attach(bufnr, true, { + on_lines = function(_, cb_bufnr) + if not bufstates[cb_bufnr].enabled then + return true + end + reset_timer(cb_bufnr) + bufstates[cb_bufnr].timer = vim.defer_fn(function() + make_request(cb_bufnr) + end, 200) + end, + on_reload = function(_, cb_bufnr) + clear(cb_bufnr) + bufstates[cb_bufnr] = nil + M.refresh({ bufnr = cb_bufnr }) + end, + on_detach = function(_, cb_bufnr) + clear(cb_bufnr) + bufstates[cb_bufnr] = nil + end, + }) + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function(opts) + clear(opts.buf) + end, + once = true, + group = augroup, + }) + end +end + +--- Disable inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +function M.disable(bufnr) + bufnr = resolve_bufnr(bufnr) + clear(bufnr) + bufstates[bufnr].enabled = nil + bufstates[bufnr].timer = nil +end + +--- Toggle inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +function M.toggle(bufnr) + bufnr = resolve_bufnr(bufnr) + local bufstate = bufstates[bufnr] + if bufstate and bufstate.enabled then + M.disable(bufnr) + else + M.enable(bufnr) + end end api.nvim_set_decoration_provider(namespace, { on_win = function(_, _, bufnr, topline, botline) - local bufstate = hint_cache_by_buf[bufnr] + local bufstate = bufstates[bufnr] if not bufstate then return end diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index e0034cf86e..c3deffc1f9 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -810,4 +810,19 @@ function M.execute_command(command_params) request('workspace/executeCommand', command_params) end +--- Enable/disable/toggle inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@param enable (boolean|nil) true/false to enable/disable, nil to toggle +function M.inlay_hint(bufnr, enable) + vim.validate({ enable = { enable, { 'boolean', 'nil' } }, bufnr = { bufnr, 'number' } }) + local inlay_hint = require('vim.lsp._inlay_hint') + if enable then + inlay_hint.enable(bufnr) + elseif enable == false then + inlay_hint.disable(bufnr) + else + inlay_hint.toggle(bufnr) + end +end + return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 44a9a58aca..284e3ef2d0 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -619,9 +619,6 @@ end ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh M['workspace/inlayHint/refresh'] = function(err, _, ctx) local inlay_hint = require('vim.lsp._inlay_hint') - if not inlay_hint.__explicit_buffers[ctx.bufnr] then - return vim.NIL - end if err then return vim.NIL end -- cgit From 96b94f8d77774e3dabdec48bba2b56246a3ccba8 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Tue, 20 Jun 2023 15:06:06 +0530 Subject: fix(lsp): duplicate on_detach, on_reload callbacks #24067 M.enable already clears bufstate[bufnr] and the namespace, the duplicate callbacks cause an error (indexing bufstate[bufnr] fails) --- runtime/lua/vim/lsp/_inlay_hint.lua | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index 70d332a1ac..bdce464480 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -48,18 +48,6 @@ function M.on_inlayhint(err, result, ctx, _) if not (bufstate.client_hint and bufstate.version) then bufstate.client_hint = vim.defaulttable() bufstate.version = ctx.version - api.nvim_buf_attach(bufnr, false, { - on_detach = function(_, cb_bufnr) - api.nvim_buf_clear_namespace(cb_bufnr, namespace, 0, -1) - bufstates[cb_bufnr].version = nil - bufstates[cb_bufnr].client_hint = nil - end, - on_reload = function(_, cb_bufnr) - api.nvim_buf_clear_namespace(cb_bufnr, namespace, 0, -1) - bufstates[cb_bufnr].version = nil - bufstates[cb_bufnr].client_hint = nil - end, - }) end local hints_by_client = bufstate.client_hint local client = vim.lsp.get_client_by_id(client_id) -- cgit From 64f2691a984a5b1e2958d5656a910054982a6f0e Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Tue, 20 Jun 2023 18:36:18 +0200 Subject: refactor(lsp): extract common execute command functionality (#24065) --- runtime/lua/vim/lsp/buf.lua | 18 ++---------------- runtime/lua/vim/lsp/codelens.lua | 24 +++--------------------- runtime/lua/vim/lsp/types.lua | 2 +- 3 files changed, 6 insertions(+), 38 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index c3deffc1f9..45056cf272 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -646,21 +646,7 @@ local function on_code_action_results(results, ctx, options) end if action.command then local command = type(action.command) == 'table' and action.command or action - local fn = client.commands[command.command] or vim.lsp.commands[command.command] - if fn then - local enriched_ctx = vim.deepcopy(ctx) - enriched_ctx.client_id = client.id - fn(command, enriched_ctx) - else - -- Not using command directly to exclude extra properties, - -- see https://github.com/python-lsp/python-lsp-server/issues/146 - local params = { - command = command.command, - arguments = command.arguments, - workDoneToken = command.workDoneToken, - } - client.request('workspace/executeCommand', params, nil, ctx.bufnr) - end + client._exec_cmd(command, ctx) end end @@ -697,7 +683,7 @@ local function on_code_action_results(results, ctx, options) return end apply_action(resolved_action, client) - end) + end, ctx.bufnr) else apply_action(action, client) end diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index e26bdcc6d4..5acfe90d5e 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -33,30 +33,12 @@ local function execute_lens(lens, bufnr, client_id) local client = vim.lsp.get_client_by_id(client_id) assert(client, 'Client is required to execute lens, client_id=' .. client_id) - local command = lens.command - local fn = client.commands[command.command] or vim.lsp.commands[command.command] - if fn then - fn(command, { bufnr = bufnr, client_id = client_id }) - return - end - -- 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.list_contains(commands, command.command) then - vim.notify( - string.format( - 'Language server does not support command `%s`. This command may require a client extension.', - command.command - ), - vim.log.levels.WARN - ) - return - end - client.request('workspace/executeCommand', command, function(...) + + client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) local result = vim.lsp.handlers['workspace/executeCommand'](...) M.refresh() return result - end, bufnr) + end) end --- Return all lenses for the given buffer diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index 108aeeb922..cdfbcfb11b 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -1,6 +1,6 @@ ---@meta ----@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil) +---@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil): any? ---@class lsp.HandlerContext ---@field method string -- cgit From d3e0352574731ae47b2ad2e4683c326ae5b2a549 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Tue, 20 Jun 2023 22:06:31 +0530 Subject: fix(lsp): check if inlay hints are enabled for a buffer before disabling (#24074) disabling before enabling throws an error otherwise, because bufstate[bufnr] doesn't exist --- runtime/lua/vim/lsp/_inlay_hint.lua | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index bdce464480..e7cc8ba7ae 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -207,9 +207,11 @@ end ---@private function M.disable(bufnr) bufnr = resolve_bufnr(bufnr) - clear(bufnr) - bufstates[bufnr].enabled = nil - bufstates[bufnr].timer = nil + if bufstates[bufnr] and bufstates[bufnr].enabled then + clear(bufnr) + bufstates[bufnr].enabled = nil + bufstates[bufnr].timer = nil + end end --- Toggle inlay hints for a buffer -- cgit From e42fdaad21a87d0aaf882f1ad836b00d2eccd21a Mon Sep 17 00:00:00 2001 From: Akin <22454918+akinsho@users.noreply.github.com> Date: Wed, 21 Jun 2023 09:55:19 +0200 Subject: fix(lsp): add spacing for inlay hints separately #24079 Problem: Spacing around inlay hints has the same highlight as the hint itself. The LSP spec for inlay hints specifically mentions the padding should not be coloured: /** Render padding before the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint. */ paddingLeft?: boolean; /** Render padding after the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint. */ paddingRight?: boolean; Solution: Add the space as separate parts of the virtual text, don't add the space to the text itself. --- runtime/lua/vim/lsp/_inlay_hint.lua | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index e7cc8ba7ae..8edf14e707 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -252,18 +252,18 @@ api.nvim_set_decoration_provider(namespace, { text = text .. part.value end end + local vt = {} if hint.paddingLeft then - text = ' ' .. text + vt[#vt + 1] = { ' ' } end + vt[#vt + 1] = { text, 'LspInlayHint' } if hint.paddingRight then - text = text .. ' ' + vt[#vt + 1] = { ' ' } end api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { virt_text_pos = 'inline', ephemeral = false, - virt_text = { - { text, 'LspInlayHint' }, - }, + virt_text = vt, hl_mode = 'combine', }) end -- cgit From 4e6356559c8cd44dbcaa765d1f39e176064526ec Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Thu, 22 Jun 2023 03:44:51 -0700 Subject: test: spellcheck :help (vimdoc) files #24109 Enforce consistent terminology (defined in `gen_help_html.lua:spell_dict`) for common misspellings. This does not spellcheck English in general (perhaps a future TODO, though it may be noisy). --- runtime/lua/vim/lsp/buf.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 45056cf272..17b444a6e8 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -159,7 +159,7 @@ end --- @param options table|nil Optional table which holds the following optional fields: --- - formatting_options (table|nil): --- Can be used to specify FormattingOptions. Some unspecified options will be ---- automatically derived from the current Neovim options. +--- automatically derived from the current Nvim options. --- See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions --- - timeout_ms (integer|nil, default 1000): --- Time in milliseconds to block for formatting requests. No effect if async=true -- cgit From 12c2c16acf7051d364d29cfd71f2542b0943d8e8 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Thu, 22 Jun 2023 19:39:57 +0200 Subject: feat(lsp): opt-in to dynamicRegistration for inlay hints (#24102) Since https://github.com/neovim/neovim/pull/23681 there is dynamic registration support. We should use that for new features unless there is a good reason to turn it off. --- runtime/lua/vim/lsp/protocol.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index b3a7903420..ea38bfe237 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -642,7 +642,7 @@ function protocol.make_client_capabilities() }, textDocument = { inlayHint = { - dynamicRegistration = false, + dynamicRegistration = true, resolveSupport = { properties = {}, }, -- cgit From 94a904b453e5fe5b2cb098828c093e34246d4125 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Fri, 23 Jun 2023 17:19:54 +0530 Subject: fix(lsp): reapplying already-applied hints #24114 Problem: The decoration provider clears the whole buffer then redraws all the hints every time the window was redrawn. This may lead to an infinite loop. Solution: Store the last applied version for a line and only clear and redraw the line if the buffer version has changed. --- runtime/lua/vim/lsp/_inlay_hint.lua | 54 ++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 25 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index 8edf14e707..66fed4f350 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -8,6 +8,7 @@ local M = {} ---@field client_hint table> client_id -> (lnum -> hints) ---@field enabled boolean Whether inlay hints are enabled for the buffer ---@field timer uv.uv_timer_t? Debounce timer associated with the buffer +---@field applied table Last version of hints applied to this line ---@type table local bufstates = {} @@ -169,7 +170,7 @@ function M.enable(bufnr) bufnr = resolve_bufnr(bufnr) local bufstate = bufstates[bufnr] if not (bufstate and bufstate.enabled) then - bufstates[bufnr] = { enabled = true, timer = nil } + bufstates[bufnr] = { enabled = true, timer = nil, applied = {} } M.refresh({ bufnr = bufnr }) api.nvim_buf_attach(bufnr, true, { on_lines = function(_, cb_bufnr) @@ -238,35 +239,38 @@ api.nvim_set_decoration_provider(namespace, { return end local hints_by_client = bufstate.client_hint - api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) for lnum = topline, botline do - for _, hints_by_lnum in pairs(hints_by_client) do - local line_hints = hints_by_lnum[lnum] or {} - for _, hint in pairs(line_hints) do - local text = '' - if type(hint.label) == 'string' then - text = hint.label - else - for _, part in ipairs(hint.label) do - text = text .. part.value + if bufstate.applied[lnum] ~= bufstate.version then + api.nvim_buf_clear_namespace(bufnr, namespace, lnum, lnum + 1) + for _, hints_by_lnum in pairs(hints_by_client) do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local text = '' + if type(hint.label) == 'string' then + text = hint.label + else + for _, part in ipairs(hint.label) do + text = text .. part.value + end end + local vt = {} + if hint.paddingLeft then + vt[#vt + 1] = { ' ' } + end + vt[#vt + 1] = { text, 'LspInlayHint' } + if hint.paddingRight then + vt[#vt + 1] = { ' ' } + end + api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { + virt_text_pos = 'inline', + ephemeral = false, + virt_text = vt, + hl_mode = 'combine', + }) end - local vt = {} - if hint.paddingLeft then - vt[#vt + 1] = { ' ' } - end - vt[#vt + 1] = { text, 'LspInlayHint' } - if hint.paddingRight then - vt[#vt + 1] = { ' ' } - end - api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { - virt_text_pos = 'inline', - ephemeral = false, - virt_text = vt, - hl_mode = 'combine', - }) end + bufstate.applied[lnum] = bufstate.version end end end, -- cgit From fa0a25dcb3a4fd2d6f03e09bcc7edac2f9ea8ded Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Sat, 24 Jun 2023 05:03:15 +0530 Subject: fix(lsp): error in reset_timer on second detach #24117 Problem: On running `zig fmt` manually, the on_lines callback and the server both detach (for some reason), and both of them call `clear()`. This fixes it, otherwise the second one to detach has an error in `reset_timer` since the bufstate doesn't exist Solution: * exit early in clear if `bufstates[bufnr]` is nil * set bufstatte.enabled to true on reload instead of making bufstate nil --- runtime/lua/vim/lsp/_inlay_hint.lua | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index 66fed4f350..84794841ae 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -144,6 +144,9 @@ end ---@private local function clear(bufnr) bufnr = resolve_bufnr(bufnr) + if not bufstates[bufnr] then + return + end reset_timer(bufnr) local bufstate = bufstates[bufnr] local client_lens = (bufstate or {}).client_hint or {} @@ -184,7 +187,9 @@ function M.enable(bufnr) end, on_reload = function(_, cb_bufnr) clear(cb_bufnr) - bufstates[cb_bufnr] = nil + if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then + bufstates[cb_bufnr] = { enabled = true } + end M.refresh({ bufnr = cb_bufnr }) end, on_detach = function(_, cb_bufnr) -- cgit From 036da0d07921e67090d1a62c9a4e382ca09d8584 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sat, 24 Jun 2023 13:47:10 +0200 Subject: fix(docs): vimdoc syntax errors gen_help_html: truncate parse-error sample text --- runtime/lua/vim/lsp/buf.lua | 6 +++--- runtime/lua/vim/lsp/util.lua | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 17b444a6e8..c2e0179cc4 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -122,7 +122,7 @@ end ---@private ---@param bufnr integer ---@param mode "v"|"V" ----@return table {start={row, col}, end={row, col}} using (1, 0) indexing +---@return table {start={row,col}, end={row,col}} using (1, 0) indexing local function range_from_selection(bufnr, mode) -- TODO: Use `vim.region()` instead https://github.com/neovim/neovim/pull/13896 @@ -189,7 +189,7 @@ end --- Restrict formatting to the client with name (client.name) matching this field. --- --- - range (table|nil) Range to format. ---- Table must contain `start` and `end` keys with {row, col} tuples using +--- Table must contain `start` and `end` keys with {row,col} tuples using --- (1,0) indexing. --- Defaults to current selection in visual mode --- Defaults to `nil` in other modes, formatting the full buffer @@ -741,7 +741,7 @@ end --- - range: (table|nil) --- Range for which code actions should be requested. --- If in visual mode this defaults to the active selection. ---- Table must contain `start` and `end` keys with {row, col} tuples +--- Table must contain `start` and `end` keys with {row,col} tuples --- using mark-like indexing. See |api-indexing| --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 538e48c805..4c319e7c41 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -178,8 +178,8 @@ local _str_byteindex_enc = M._str_byteindex_enc --- CAUTION: Changes in-place! --- ---@param lines (table) Original list of strings ----@param A (table) Start position; a 2-tuple of {line, col} numbers ----@param B (table) End position; a 2-tuple of {line, col} numbers +---@param A (table) Start position; a 2-tuple of {line,col} numbers +---@param B (table) End position; a 2-tuple of {line,col} numbers ---@param new_lines A list of strings to replace the original ---@returns (table) The modified {lines} object function M.set_lines(lines, A, B, new_lines) @@ -2075,9 +2075,9 @@ end --- Using the given range in the current buffer, creates an object that --- is similar to |vim.lsp.util.make_range_params()|. --- ----@param start_pos integer[]|nil {row, col} mark-indexed position. +---@param start_pos integer[]|nil {row,col} mark-indexed position. --- Defaults to the start of the last visual selection. ----@param end_pos integer[]|nil {row, col} mark-indexed position. +---@param end_pos integer[]|nil {row,col} mark-indexed position. --- Defaults to the end of the last visual selection. ---@param bufnr integer|nil buffer handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` -- cgit From 7968322e7a20b557631f4b496751658e80f6e7b0 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Thu, 29 Jun 2023 19:56:29 +0530 Subject: fix(lsp): inlay_hint nil reference error #24202 Problem: vim_lsp_inlayhint: Error executing lua: .../lsp/_inlay_hint.lua:249: attempt to index field 'applied' (a nil value) Solution: Assign {} to bufstates.applied in on_reload fixes #24172 --- runtime/lua/vim/lsp/_inlay_hint.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua index 84794841ae..ccf1b5cca4 100644 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ b/runtime/lua/vim/lsp/_inlay_hint.lua @@ -188,7 +188,7 @@ function M.enable(bufnr) on_reload = function(_, cb_bufnr) clear(cb_bufnr) if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then - bufstates[cb_bufnr] = { enabled = true } + bufstates[cb_bufnr] = { enabled = true, applied = {} } end M.refresh({ bufnr = cb_bufnr }) end, -- cgit From 37079fca58f396fd866dc7b7d87a0100c17ee760 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Fri, 30 Jun 2023 11:33:28 +0200 Subject: feat(lsp): move inlay_hint() to vim.lsp (#24130) Allows to keep more functions hidden and gives a path forward for further inlay_hint related functions - like applying textEdits. See https://github.com/neovim/neovim/pull/23984#pullrequestreview-1486624668 --- runtime/lua/vim/lsp/_inlay_hint.lua | 284 -------------------------------- runtime/lua/vim/lsp/buf.lua | 15 -- runtime/lua/vim/lsp/handlers.lua | 20 +-- runtime/lua/vim/lsp/inlay_hint.lua | 313 ++++++++++++++++++++++++++++++++++++ 4 files changed, 316 insertions(+), 316 deletions(-) delete mode 100644 runtime/lua/vim/lsp/_inlay_hint.lua create mode 100644 runtime/lua/vim/lsp/inlay_hint.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_inlay_hint.lua b/runtime/lua/vim/lsp/_inlay_hint.lua deleted file mode 100644 index ccf1b5cca4..0000000000 --- a/runtime/lua/vim/lsp/_inlay_hint.lua +++ /dev/null @@ -1,284 +0,0 @@ -local util = require('vim.lsp.util') -local log = require('vim.lsp.log') -local api = vim.api -local M = {} - ----@class lsp._inlay_hint.bufstate ----@field version integer ----@field client_hint table> client_id -> (lnum -> hints) ----@field enabled boolean Whether inlay hints are enabled for the buffer ----@field timer uv.uv_timer_t? Debounce timer associated with the buffer ----@field applied table Last version of hints applied to this line - ----@type table -local bufstates = {} - -local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') -local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) - ---- Reset the request debounce timer of a buffer ----@private -local function reset_timer(reset_bufnr) - local timer = bufstates[reset_bufnr].timer - if timer then - bufstates[reset_bufnr].timer = nil - if not timer:is_closing() then - timer:stop() - timer:close() - end - end -end - ---- |lsp-handler| for the method `textDocument/inlayHint` ---- Store hints for a specific buffer and client ----@private -function M.on_inlayhint(err, result, ctx, _) - if err then - local _ = log.error() and log.error('inlayhint', err) - return - end - local bufnr = ctx.bufnr - if util.buf_versions[bufnr] ~= ctx.version then - return - end - local client_id = ctx.client_id - if not result then - return - end - local bufstate = bufstates[bufnr] - if not (bufstate.client_hint and bufstate.version) then - bufstate.client_hint = vim.defaulttable() - bufstate.version = ctx.version - end - local hints_by_client = bufstate.client_hint - local client = vim.lsp.get_client_by_id(client_id) - - local new_hints_by_lnum = vim.defaulttable() - local num_unprocessed = #result - if num_unprocessed == 0 then - hints_by_client[client_id] = {} - bufstate.version = ctx.version - api.nvim__buf_redraw_range(bufnr, 0, -1) - return - end - - local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) - ---@private - local function pos_to_byte(position) - local col = position.character - if col > 0 then - local line = lines[position.line + 1] or '' - local ok, convert_result - ok, convert_result = pcall(util._str_byteindex_enc, line, col, client.offset_encoding) - if ok then - return convert_result - end - return math.min(#line, col) - end - return col - end - - for _, hint in ipairs(result) do - local lnum = hint.position.line - hint.position.character = pos_to_byte(hint.position) - table.insert(new_hints_by_lnum[lnum], hint) - end - - hints_by_client[client_id] = new_hints_by_lnum - bufstate.version = ctx.version - api.nvim__buf_redraw_range(bufnr, 0, -1) -end - ----@private -local function resolve_bufnr(bufnr) - return bufnr > 0 and bufnr or api.nvim_get_current_buf() -end - ---- Refresh inlay hints for a buffer ---- ----@param opts (nil|table) Optional arguments ---- - bufnr (integer, default: 0): Buffer whose hints to refresh ---- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer ---- ----@private -function M.refresh(opts) - opts = opts or {} - local bufnr = resolve_bufnr(opts.bufnr or 0) - local bufstate = bufstates[bufnr] - if not (bufstate and bufstate.enabled) then - return - end - local only_visible = opts.only_visible or false - local buffer_windows = {} - for _, winid in ipairs(api.nvim_list_wins()) do - if api.nvim_win_get_buf(winid) == bufnr then - table.insert(buffer_windows, winid) - end - end - for _, window in ipairs(buffer_windows) do - local first = vim.fn.line('w0', window) - local last = vim.fn.line('w$', window) - local params = { - textDocument = util.make_text_document_params(bufnr), - range = { - start = { line = first - 1, character = 0 }, - ['end'] = { line = last, character = 0 }, - }, - } - vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) - end - if not only_visible then - local params = { - textDocument = util.make_text_document_params(bufnr), - range = { - start = { line = 0, character = 0 }, - ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, - }, - } - vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) - end -end - ---- Clear inlay hints ----@param bufnr (integer) Buffer handle, or 0 for current ----@private -local function clear(bufnr) - bufnr = resolve_bufnr(bufnr) - if not bufstates[bufnr] then - return - end - reset_timer(bufnr) - local bufstate = bufstates[bufnr] - local client_lens = (bufstate or {}).client_hint or {} - local client_ids = vim.tbl_keys(client_lens) - for _, iter_client_id in ipairs(client_ids) do - if bufstate then - bufstate.client_hint[iter_client_id] = {} - end - end - api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) - api.nvim__buf_redraw_range(bufnr, 0, -1) -end - ----@private -local function make_request(request_bufnr) - reset_timer(request_bufnr) - M.refresh({ bufnr = request_bufnr }) -end - ---- Enable inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current ----@private -function M.enable(bufnr) - bufnr = resolve_bufnr(bufnr) - local bufstate = bufstates[bufnr] - if not (bufstate and bufstate.enabled) then - bufstates[bufnr] = { enabled = true, timer = nil, applied = {} } - M.refresh({ bufnr = bufnr }) - api.nvim_buf_attach(bufnr, true, { - on_lines = function(_, cb_bufnr) - if not bufstates[cb_bufnr].enabled then - return true - end - reset_timer(cb_bufnr) - bufstates[cb_bufnr].timer = vim.defer_fn(function() - make_request(cb_bufnr) - end, 200) - end, - on_reload = function(_, cb_bufnr) - clear(cb_bufnr) - if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then - bufstates[cb_bufnr] = { enabled = true, applied = {} } - end - M.refresh({ bufnr = cb_bufnr }) - end, - on_detach = function(_, cb_bufnr) - clear(cb_bufnr) - bufstates[cb_bufnr] = nil - end, - }) - api.nvim_create_autocmd('LspDetach', { - buffer = bufnr, - callback = function(opts) - clear(opts.buf) - end, - once = true, - group = augroup, - }) - end -end - ---- Disable inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current ----@private -function M.disable(bufnr) - bufnr = resolve_bufnr(bufnr) - if bufstates[bufnr] and bufstates[bufnr].enabled then - clear(bufnr) - bufstates[bufnr].enabled = nil - bufstates[bufnr].timer = nil - end -end - ---- Toggle inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current ----@private -function M.toggle(bufnr) - bufnr = resolve_bufnr(bufnr) - local bufstate = bufstates[bufnr] - if bufstate and bufstate.enabled then - M.disable(bufnr) - else - M.enable(bufnr) - end -end - -api.nvim_set_decoration_provider(namespace, { - on_win = function(_, _, bufnr, topline, botline) - local bufstate = bufstates[bufnr] - if not bufstate then - return - end - - if bufstate.version ~= util.buf_versions[bufnr] then - return - end - local hints_by_client = bufstate.client_hint - - for lnum = topline, botline do - if bufstate.applied[lnum] ~= bufstate.version then - api.nvim_buf_clear_namespace(bufnr, namespace, lnum, lnum + 1) - for _, hints_by_lnum in pairs(hints_by_client) do - local line_hints = hints_by_lnum[lnum] or {} - for _, hint in pairs(line_hints) do - local text = '' - if type(hint.label) == 'string' then - text = hint.label - else - for _, part in ipairs(hint.label) do - text = text .. part.value - end - end - local vt = {} - if hint.paddingLeft then - vt[#vt + 1] = { ' ' } - end - vt[#vt + 1] = { text, 'LspInlayHint' } - if hint.paddingRight then - vt[#vt + 1] = { ' ' } - end - api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { - virt_text_pos = 'inline', - ephemeral = false, - virt_text = vt, - hl_mode = 'combine', - }) - end - end - bufstate.applied[lnum] = bufstate.version - end - end - end, -}) - -return M diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index c2e0179cc4..0369725216 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -796,19 +796,4 @@ function M.execute_command(command_params) request('workspace/executeCommand', command_params) end ---- Enable/disable/toggle inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current ----@param enable (boolean|nil) true/false to enable/disable, nil to toggle -function M.inlay_hint(bufnr, enable) - vim.validate({ enable = { enable, { 'boolean', 'nil' } }, bufnr = { bufnr, 'number' } }) - local inlay_hint = require('vim.lsp._inlay_hint') - if enable then - inlay_hint.enable(bufnr) - elseif enable == false then - inlay_hint.disable(bufnr) - else - inlay_hint.toggle(bufnr) - end -end - return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 284e3ef2d0..625a2ed282 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -220,7 +220,7 @@ M['textDocument/codeLens'] = function(...) end M['textDocument/inlayHint'] = function(...) - return require('vim.lsp._inlay_hint').on_inlayhint(...) + return require('vim.lsp.inlay_hint').on_inlayhint(...) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references @@ -617,22 +617,8 @@ M['window/showDocument'] = function(_, result, ctx, _) end ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh -M['workspace/inlayHint/refresh'] = function(err, _, ctx) - local inlay_hint = require('vim.lsp._inlay_hint') - if err then - return vim.NIL - end - - for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do - for _, winid in ipairs(api.nvim_list_wins()) do - if api.nvim_win_get_buf(winid) == bufnr then - inlay_hint.refresh({ bufnr = bufnr }) - break - end - end - end - - return vim.NIL +M['workspace/inlayHint/refresh'] = function(err, result, ctx, config) + return require('vim.lsp.inlay_hint').on_refresh(err, result, ctx, config) end -- Add boilerplate error validation and logging for all of these. diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua new file mode 100644 index 0000000000..1af18bbc61 --- /dev/null +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -0,0 +1,313 @@ +local util = require('vim.lsp.util') +local log = require('vim.lsp.log') +local api = vim.api +local M = {} + +---@class lsp._inlay_hint.bufstate +---@field version integer +---@field client_hint table> client_id -> (lnum -> hints) +---@field enabled boolean Whether inlay hints are enabled for the buffer +---@field timer uv.uv_timer_t? Debounce timer associated with the buffer +---@field applied table Last version of hints applied to this line + +---@type table +local bufstates = {} + +local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') +local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) + +--- Reset the request debounce timer of a buffer +---@private +local function reset_timer(reset_bufnr) + local timer = bufstates[reset_bufnr].timer + if timer then + bufstates[reset_bufnr].timer = nil + if not timer:is_closing() then + timer:stop() + timer:close() + end + end +end + +--- |lsp-handler| for the method `textDocument/inlayHint` +--- Store hints for a specific buffer and client +---@private +function M.on_inlayhint(err, result, ctx, _) + if err then + local _ = log.error() and log.error('inlayhint', err) + return + end + local bufnr = ctx.bufnr + if util.buf_versions[bufnr] ~= ctx.version then + return + end + local client_id = ctx.client_id + if not result then + return + end + local bufstate = bufstates[bufnr] + if not (bufstate.client_hint and bufstate.version) then + bufstate.client_hint = vim.defaulttable() + bufstate.version = ctx.version + end + local hints_by_client = bufstate.client_hint + local client = vim.lsp.get_client_by_id(client_id) + + local new_hints_by_lnum = vim.defaulttable() + local num_unprocessed = #result + if num_unprocessed == 0 then + hints_by_client[client_id] = {} + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) + return + end + + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) + ---@private + local function pos_to_byte(position) + local col = position.character + if col > 0 then + local line = lines[position.line + 1] or '' + local ok, convert_result + ok, convert_result = pcall(util._str_byteindex_enc, line, col, client.offset_encoding) + if ok then + return convert_result + end + return math.min(#line, col) + end + return col + end + + for _, hint in ipairs(result) do + local lnum = hint.position.line + hint.position.character = pos_to_byte(hint.position) + table.insert(new_hints_by_lnum[lnum], hint) + end + + hints_by_client[client_id] = new_hints_by_lnum + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +---@private +local function resolve_bufnr(bufnr) + return bufnr > 0 and bufnr or api.nvim_get_current_buf() +end + +--- Refresh inlay hints for a buffer +--- +---@param opts (nil|table) Optional arguments +--- - bufnr (integer, default: 0): Buffer whose hints to refresh +--- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer +--- +---@private +local function refresh(opts) + opts = opts or {} + local bufnr = resolve_bufnr(opts.bufnr or 0) + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.enabled) then + return + end + local only_visible = opts.only_visible or false + local buffer_windows = {} + for _, winid in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(winid) == bufnr then + table.insert(buffer_windows, winid) + end + end + for _, window in ipairs(buffer_windows) do + local first = vim.fn.line('w0', window) + local last = vim.fn.line('w$', window) + local params = { + textDocument = util.make_text_document_params(bufnr), + range = { + start = { line = first - 1, character = 0 }, + ['end'] = { line = last, character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) + end + if not only_visible then + local params = { + textDocument = util.make_text_document_params(bufnr), + range = { + start = { line = 0, character = 0 }, + ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) + end +end + +--- |lsp-handler| for the method `textDocument/inlayHint/refresh` +---@private +function M.on_refresh(err, _, ctx, _) + if err then + return vim.NIL + end + for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do + for _, winid in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(winid) == bufnr then + refresh({ bufnr = bufnr }) + break + end + end + end + + return vim.NIL +end + +--- Clear inlay hints +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +local function clear(bufnr) + bufnr = resolve_bufnr(bufnr) + if not bufstates[bufnr] then + return + end + reset_timer(bufnr) + local bufstate = bufstates[bufnr] + local client_lens = (bufstate or {}).client_hint or {} + local client_ids = vim.tbl_keys(client_lens) + for _, iter_client_id in ipairs(client_ids) do + if bufstate then + bufstate.client_hint[iter_client_id] = {} + end + end + api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +---@private +local function make_request(request_bufnr) + reset_timer(request_bufnr) + refresh({ bufnr = request_bufnr }) +end + +--- Enable inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +local function enable(bufnr) + bufnr = resolve_bufnr(bufnr) + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.enabled) then + bufstates[bufnr] = { enabled = true, timer = nil, applied = {} } + refresh({ bufnr = bufnr }) + api.nvim_buf_attach(bufnr, true, { + on_lines = function(_, cb_bufnr) + if not bufstates[cb_bufnr].enabled then + return true + end + reset_timer(cb_bufnr) + bufstates[cb_bufnr].timer = vim.defer_fn(function() + make_request(cb_bufnr) + end, 200) + end, + on_reload = function(_, cb_bufnr) + clear(cb_bufnr) + if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then + bufstates[cb_bufnr] = { enabled = true, applied = {} } + end + refresh({ bufnr = cb_bufnr }) + end, + on_detach = function(_, cb_bufnr) + clear(cb_bufnr) + bufstates[cb_bufnr] = nil + end, + }) + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function(opts) + clear(opts.buf) + end, + once = true, + group = augroup, + }) + end +end + +--- Disable inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +local function disable(bufnr) + bufnr = resolve_bufnr(bufnr) + if bufstates[bufnr] and bufstates[bufnr].enabled then + clear(bufnr) + bufstates[bufnr].enabled = nil + bufstates[bufnr].timer = nil + end +end + +--- Toggle inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +local function toggle(bufnr) + bufnr = resolve_bufnr(bufnr) + local bufstate = bufstates[bufnr] + if bufstate and bufstate.enabled then + M.disable(bufnr) + else + M.enable(bufnr) + end +end + +api.nvim_set_decoration_provider(namespace, { + on_win = function(_, _, bufnr, topline, botline) + local bufstate = bufstates[bufnr] + if not bufstate then + return + end + + if bufstate.version ~= util.buf_versions[bufnr] then + return + end + local hints_by_client = bufstate.client_hint + + for lnum = topline, botline do + if bufstate.applied[lnum] ~= bufstate.version then + api.nvim_buf_clear_namespace(bufnr, namespace, lnum, lnum + 1) + for _, hints_by_lnum in pairs(hints_by_client) do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local text = '' + if type(hint.label) == 'string' then + text = hint.label + else + for _, part in ipairs(hint.label) do + text = text .. part.value + end + end + local vt = {} + if hint.paddingLeft then + vt[#vt + 1] = { ' ' } + end + vt[#vt + 1] = { text, 'LspInlayHint' } + if hint.paddingRight then + vt[#vt + 1] = { ' ' } + end + api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { + virt_text_pos = 'inline', + ephemeral = false, + virt_text = vt, + hl_mode = 'combine', + }) + end + end + bufstate.applied[lnum] = bufstate.version + end + end + end, +}) + +return setmetatable(M, { + __call = function(_, bufnr, enable_) + vim.validate({ enable = { enable_, { 'boolean', 'nil' } }, bufnr = { bufnr, 'number' } }) + if enable_ then + enable(bufnr) + elseif enable_ == false then + disable(bufnr) + else + toggle(bufnr) + end + end, +}) -- cgit From d191bdf9d5e54722e28ddb0cccc8eb2312a234df Mon Sep 17 00:00:00 2001 From: Sanchayan Maity Date: Fri, 30 Jun 2023 17:12:58 +0530 Subject: fix(lsp): fix attempt to call non existent function (#24212) Commit 37079fc moved inlay_hint to vim.lsp() but in the process did missed converting a call to disable/enable which are now local. Fixes the below error when trying to toggle inlay hints. E5108: Error executing lua /usr/local/share/nvim/runtime/lua/vim/lsp/inlay_hint.lua:248: attempt to call field 'disable' (a nil value) stack traceback: /usr/local/share/nvim/runtime/lua/vim/lsp/inlay_hint.lua:248: in function 'toggle' /usr/local/share/nvim/runtime/lua/vim/lsp/inlay_hint.lua:310: in function 'inlay_hint' [string ":lua"]:1: in main chunk --- runtime/lua/vim/lsp/inlay_hint.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 1af18bbc61..f577a31696 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -245,9 +245,9 @@ local function toggle(bufnr) bufnr = resolve_bufnr(bufnr) local bufstate = bufstates[bufnr] if bufstate and bufstate.enabled then - M.disable(bufnr) + disable(bufnr) else - M.enable(bufnr) + enable(bufnr) end end -- cgit From ba8f19ebb67ca27d746f4b1cd902ab3d807eace3 Mon Sep 17 00:00:00 2001 From: Raphael Date: Sat, 1 Jul 2023 18:42:37 +0800 Subject: fix(lsp): lint warnings, default offset_encoding #24046 - fix lint / analysis warnings - locations_to_items(): get default offset_encoding from active client - character_offset(): get default offset_encoding from active client --- runtime/lua/vim/lsp/buf.lua | 6 +- runtime/lua/vim/lsp/codelens.lua | 4 +- runtime/lua/vim/lsp/log.lua | 2 +- runtime/lua/vim/lsp/protocol.lua | 11 +++- runtime/lua/vim/lsp/rpc.lua | 2 +- runtime/lua/vim/lsp/util.lua | 134 +++++++++++++++++++++------------------ 6 files changed, 85 insertions(+), 74 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 0369725216..c742505ec6 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -581,9 +581,9 @@ function M.document_highlight() end --- Removes document highlights from current buffer. ---- -function M.clear_references() - util.buf_clear_references() +--- @param bufnr integer|nil +function M.clear_references(bufnr) + util.buf_clear_references(bufnr or 0) end ---@private diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 5acfe90d5e..67104cc40b 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -33,11 +33,9 @@ local function execute_lens(lens, bufnr, client_id) local client = vim.lsp.get_client_by_id(client_id) assert(client, 'Client is required to execute lens, client_id=' .. client_id) - client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) - local result = vim.lsp.handlers['workspace/executeCommand'](...) + vim.lsp.handlers['workspace/executeCommand'](...) M.refresh() - return result end) end diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index 07d0500797..c77e7c045b 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -154,7 +154,7 @@ function log.set_level(level) end --- Gets the current log level. ----@return string current log level +---@return integer current log level function log.get_level() return current_log_level end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index ea38bfe237..27da891656 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -880,7 +880,7 @@ end --- Creates a normalized object describing LSP server capabilities. ---@param server_capabilities table Table of capabilities supported by the server ----@return table Normalized table of capabilities +---@return table|nil Normalized table of capabilities function protocol.resolve_capabilities(server_capabilities) local TextDocumentSyncKind = protocol.TextDocumentSyncKind local textDocumentSync = server_capabilities.textDocumentSync @@ -898,7 +898,8 @@ function protocol.resolve_capabilities(server_capabilities) elseif type(textDocumentSync) == 'number' then -- Backwards compatibility if not TextDocumentSyncKind[textDocumentSync] then - return nil, 'Invalid server TextDocumentSyncKind for textDocumentSync' + vim.notify('Invalid server TextDocumentSyncKind for textDocumentSync', vim.log.levels.ERROR) + return nil end server_capabilities.textDocumentSync = { openClose = true, @@ -910,7 +911,11 @@ function protocol.resolve_capabilities(server_capabilities) }, } elseif type(textDocumentSync) ~= 'table' then - return nil, string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)) + vim.notify( + string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)), + vim.log.levels.ERROR + ) + return nil end return server_capabilities end diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 64bc732bdf..6552eaa800 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -36,7 +36,7 @@ end local function parse_headers(header) assert(type(header) == 'string', 'header must be a string') local headers = {} - for line in vim.gsplit(header, '\r\n', true) do + for line in vim.gsplit(header, '\r\n', { plain = true }) do if line == '' then break end diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 4c319e7c41..6cb91417f2 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -25,9 +25,9 @@ local default_border = { ---@private --- Check the border given by opts or the default border for the additional --- size it adds to a float. ----@param opts (table, optional) options for the floating window +---@param opts table optional options for the floating window --- - border (string or table) the border ----@returns (table) size of border in the form of { height = height, width = width } +---@return table size of border in the form of { height = height, width = width } local function get_border_size(opts) local border = opts and opts.border or default_border local height = 0 @@ -106,7 +106,7 @@ end ---@private local function split_lines(value) value = string.gsub(value, '\r\n?', '\n') - return split(value, '\n', true) + return split(value, '\n', { plain = true }) end ---@private @@ -122,7 +122,7 @@ end --- Convenience wrapper around vim.str_utfindex ---@param line string line to be indexed ---@param index integer|nil byte index (utf-8), or `nil` for length ----@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 +---@param encoding string|nil utf-8|utf-16|utf-32|nil defaults to utf-16 ---@return integer `encoding` index of `index` in `line` function M._str_utfindex_enc(line, index, encoding) if not encoding then @@ -150,7 +150,7 @@ end ---Alternative to vim.str_byteindex that takes an encoding. ---@param line string line to be indexed ---@param index integer UTF index ----@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 +---@param encoding string utf-8|utf-16|utf-32| defaults to utf-16 ---@return integer byte (utf-8) index of `encoding` index `index` in `line` function M._str_byteindex_enc(line, index, encoding) if not encoding then @@ -180,8 +180,8 @@ local _str_byteindex_enc = M._str_byteindex_enc ---@param lines (table) Original list of strings ---@param A (table) Start position; a 2-tuple of {line,col} numbers ---@param B (table) End position; a 2-tuple of {line,col} numbers ----@param new_lines A list of strings to replace the original ----@returns (table) The modified {lines} object +---@param new_lines (table) list of strings to replace the original +---@return table The modified {lines} object function M.set_lines(lines, A, B, new_lines) -- 0-indexing to 1-indexing local i_0 = A[1] + 1 @@ -241,7 +241,7 @@ end --- ---@param bufnr integer bufnr to get the lines from ---@param rows integer[] zero-indexed line numbers ----@return table a table mapping rows to lines +---@return table|string a table mapping rows to lines local function get_lines(bufnr, rows) rows = type(rows) == 'table' and rows or { rows } @@ -331,8 +331,9 @@ end ---@private --- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position --- Returns a zero-indexed column, since set_lines() does the conversion to ----@param offset_encoding string utf-8|utf-16|utf-32 +---@param offset_encoding string|nil utf-8|utf-16|utf-32 --- 1-indexed +---@return integer local function get_line_byte_from_position(bufnr, position, offset_encoding) -- LSP's line and characters are 0-indexed -- Vim's line and columns are 1-indexed @@ -598,8 +599,8 @@ end --- Can be used to extract the completion items from a --- `textDocument/completion` request, which may return one of --- `CompletionItem[]`, `CompletionList` or null. ----@param result (table) The result of a `textDocument/completion` request ----@returns (table) List of completion items +---@param result table The result of a `textDocument/completion` request +---@return table List of completion items ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion function M.extract_completion_items(result) if type(result) == 'table' and result.items then @@ -658,7 +659,7 @@ end --- Parses snippets in a completion entry. --- ---@param input string unparsed snippet ----@returns string parsed snippet +---@return string parsed snippet function M.parse_snippet(input) local ok, parsed = pcall(function() return tostring(snippet.parse(input)) @@ -718,7 +719,7 @@ end --- specification. --- ---@param completion_item_kind (`vim.lsp.protocol.completionItemKind`) ----@returns (`vim.lsp.protocol.completionItemKind`) +---@return (`vim.lsp.protocol.completionItemKind`) ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion function M._get_completion_item_kind_name(completion_item_kind) return protocol.CompletionItemKind[completion_item_kind] or 'Unknown' @@ -727,12 +728,12 @@ end --- Turns the result of a `textDocument/completion` request into vim-compatible --- |complete-items|. --- ----@param result The result of a `textDocument/completion` call, e.g. from +---@param result table The result of a `textDocument/completion` call, e.g. from ---|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, --- `CompletionList` or `null` ---@param prefix (string) the prefix to filter the completion items ----@returns { matches = complete-items table, incomplete = bool } ----@see |complete-items| +---@return table { matches = complete-items table, incomplete = bool } +---@see complete-items function M.text_document_completion_list_to_complete_items(result, prefix) local items = M.extract_completion_items(result) if vim.tbl_isempty(items) then @@ -937,7 +938,7 @@ end --- ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ----@returns {contents}, extended with lines of converted markdown. +---@return table {contents} extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover function M.convert_input_to_markdown_lines(input, contents) contents = contents or {} @@ -985,10 +986,11 @@ end --- Converts `textDocument/SignatureHelp` response to markdown lines. --- ----@param signature_help Response of `textDocument/SignatureHelp` ----@param ft optional filetype that will be use as the `lang` for the label markdown code block ----@param triggers optional list of trigger characters from the lsp server. used to better determine parameter offsets ----@returns list of lines of converted markdown. +---@param signature_help table Response of `textDocument/SignatureHelp` +---@param ft string|nil filetype that will be use as the `lang` for the label markdown code block +---@param triggers table|nil list of trigger characters from the lsp server. used to better determine parameter offsets +---@return table|nil table list of lines of converted markdown. +---@return table|nil table of active hl ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers) if not signature_help.signatures then @@ -1015,7 +1017,7 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers -- wrap inside a code block so stylize_markdown can render it properly label = ('```%s\n%s\n```'):format(ft, label) end - list_extend(contents, split(label, '\n', true)) + list_extend(contents, split(label, '\n', { plain = true })) if signature.documentation then M.convert_input_to_markdown_lines(signature.documentation, contents) end @@ -1087,16 +1089,16 @@ end --- Creates a table with sensible default options for a floating window. The --- table can be passed to |nvim_open_win()|. --- ----@param width (integer) window width (in character cells) ----@param height (integer) window height (in character cells) ----@param opts (table, optional) +---@param width integer window width (in character cells) +---@param height integer window height (in character cells) +---@param opts table optional --- - offset_x (integer) offset to add to `col` --- - offset_y (integer) offset to add to `row` --- - border (string or table) override `border` --- - focusable (string or table) override `focusable` --- - zindex (string or table) override `zindex`, defaults to 50 --- - relative ("mouse"|"cursor") defaults to "cursor" ----@returns (table) Options +---@return table Options function M.make_floating_popup_options(width, height, opts) validate({ opts = { opts, 't', true }, @@ -1160,7 +1162,7 @@ end --- Shows document and optionally jumps to the location. --- ---@param location table (`Location`|`LocationLink`) ----@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---@param opts table|nil options --- - reuse_win (boolean) Jump to existing window if buffer is already open. --- - focus (boolean) Whether to focus/jump to location if possible. Defaults to true. @@ -1217,7 +1219,7 @@ end --- Jumps to a location. --- ---@param location table (`Location`|`LocationLink`) ----@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---@param reuse_win boolean|nil Jump to existing window if buffer is already open. ---@return boolean `true` if the jump succeeded function M.jump_to_location(location, offset_encoding, reuse_win) @@ -1237,8 +1239,9 @@ end --- - for Location, range is shown (e.g., function definition) --- - for LocationLink, targetRange is shown (e.g., body of function definition) --- ----@param location a single `Location` or `LocationLink` ----@returns (bufnr,winnr) buffer and window number of floating window or nil +---@param location table a single `Location` or `LocationLink` +---@return integer|nil buffer id of float window +---@return integer|nil window id of float window function M.preview_location(location, opts) -- location may be LocationLink or Location (more useful for the former) local uri = location.targetUri or location.uri @@ -1275,10 +1278,10 @@ end --- Trims empty lines from input and pad top and bottom with empty lines --- ---@param contents table of lines to trim and pad ----@param opts dictionary with optional fields +---@param opts table with optional fields --- - pad_top number of lines to pad contents at top (default 0) --- - pad_bottom number of lines to pad contents at bottom (default 0) ----@return contents table of trimmed and padded lines +---@return table table of trimmed and padded lines function M._trim(contents, opts) validate({ contents = { contents, 't' }, @@ -1301,7 +1304,7 @@ end --- Generates a table mapping markdown code block lang to vim syntax, --- based on g:markdown_fenced_languages ----@return a table of lang -> syntax mappings +---@return table table of lang -> syntax mappings ---@private local function get_markdown_fences() local fences = {} @@ -1324,7 +1327,7 @@ end --- If you want to open a popup with fancy markdown, use `open_floating_preview` instead --- ---@param contents table of lines to show in window ----@param opts dictionary with optional fields +---@param opts table with optional fields --- - height of floating window --- - width of floating window --- - wrap_at character to wrap at for computing height @@ -1333,7 +1336,7 @@ end --- - pad_top number of lines to pad contents at top --- - pad_bottom number of lines to pad contents at bottom --- - separator insert separator after code block ----@returns width,height size of float +---@return table stripped content function M.stylize_markdown(bufnr, contents, opts) validate({ contents = { contents, 't' }, @@ -1480,10 +1483,10 @@ function M.stylize_markdown(bufnr, contents, opts) if not langs[lang] then -- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set pcall(api.nvim_buf_del_var, bufnr, 'current_syntax') - -- TODO(ashkan): better validation before this. - if not pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) then + if #api.nvim_get_runtime_file(('syntax/%s.vim'):format(ft), true) == 0 then return end + vim.cmd(string.format('syntax include %s syntax/%s.vim', lang, ft)) langs[lang] = true end vim.cmd( @@ -1542,7 +1545,7 @@ end ---@param events table list of events ---@param winnr integer window id of preview window ---@param bufnrs table list of buffers where the preview window will remain visible ----@see |autocmd-events| +---@see autocmd-events local function close_preview_autocmd(events, winnr, bufnrs) local augroup = api.nvim_create_augroup('preview_window_' .. winnr, { clear = true, @@ -1572,13 +1575,14 @@ end --- Computes size of float needed to show contents (with optional wrapping) --- ---@param contents table of lines to show in window ----@param opts dictionary with optional fields +---@param opts table with optional fields --- - height of floating window --- - width of floating window --- - wrap_at character to wrap at for computing height --- - max_width maximal width of floating window --- - max_height maximal height of floating window ----@returns width,height size of float +---@return integer width size of float +---@return integer height size of float function M._make_floating_popup_size(contents, opts) validate({ contents = { contents, 't' }, @@ -1662,7 +1666,8 @@ end --- - focus: (boolean, default true) If `true`, and if {focusable} --- is also `true`, focus an existing floating window with the same --- {focus_id} ----@returns bufnr,winnr buffer and window number of the newly created floating +---@return integer bufnr of newly created float window +---@return integer winid of newly created float window ---preview window function M.open_floating_preview(contents, syntax, opts) validate({ @@ -1766,7 +1771,7 @@ do --[[ References ]] --- ---@param bufnr integer Buffer id function M.buf_clear_references(bufnr) - validate({ bufnr = { bufnr, 'n', true } }) + validate({ bufnr = { bufnr, { 'n', 'nil' }, true } }) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) end @@ -1828,13 +1833,15 @@ end) --- ---@param locations table list of `Location`s or `LocationLink`s ---@param offset_encoding string offset_encoding for locations utf-8|utf-16|utf-32 ----@returns (table) list of items +--- default to first client of buffer +---@return table list of items function M.locations_to_items(locations, offset_encoding) if offset_encoding == nil then vim.notify_once( 'locations_to_items must be called with valid offset encoding', vim.log.levels.WARN ) + offset_encoding = vim.lsp.get_active_clients({ bufnr = 0 })[1].offset_encoding end local items = {} @@ -1896,7 +1903,7 @@ end --- Converts symbols to quickfix list items. --- ----@param symbols DocumentSymbol[] or SymbolInformation[] +---@param symbols table DocumentSymbol[] or SymbolInformation[] function M.symbols_to_items(symbols, bufnr) ---@private local function _symbols_to_items(_symbols, _items, _bufnr) @@ -1936,8 +1943,8 @@ function M.symbols_to_items(symbols, bufnr) end --- Removes empty lines from the beginning and end. ----@param lines (table) list of lines to trim ----@returns (table) trimmed list of lines +---@param lines table list of lines to trim +---@return table trimmed list of lines function M.trim_empty_lines(lines) local start = 1 for i = 1, #lines do @@ -1961,8 +1968,8 @@ end --- --- CAUTION: Modifies the input in-place! --- ----@param lines (table) list of lines ----@returns (string) filetype or "markdown" if it was unchanged. +---@param lines table list of lines +---@return string filetype or "markdown" if it was unchanged. function M.try_trim_markdown_code_blocks(lines) local language_id = lines[1]:match('^```(.*)') if language_id then @@ -2007,7 +2014,7 @@ end --- ---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ----@returns `TextDocumentPositionParams` object +---@return table `TextDocumentPositionParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams function M.make_position_params(window, offset_encoding) window = window or 0 @@ -2021,7 +2028,7 @@ end --- Utility function for getting the encoding of the first LSP client on the given buffer. ---@param bufnr (integer) buffer handle or 0 for current, defaults to current ----@returns (string) encoding first client if there is one, nil otherwise +---@return string encoding first client if there is one, nil otherwise function M._get_offset_encoding(bufnr) validate({ bufnr = { bufnr, 'n', true }, @@ -2060,7 +2067,7 @@ end --- ---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window` ----@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@return table { textDocument = { uri = `current_file_uri` }, range = { start = ---`current_position`, end = `current_position` } } function M.make_range_params(window, offset_encoding) local buf = api.nvim_win_get_buf(window or 0) @@ -2081,7 +2088,7 @@ end --- Defaults to the end of the last visual selection. ---@param bufnr integer|nil buffer handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` ----@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@return table { textDocument = { uri = `current_file_uri` }, range = { start = ---`start_position`, end = `end_position` } } function M.make_given_range_params(start_pos, end_pos, bufnr, offset_encoding) validate({ @@ -2121,15 +2128,15 @@ end --- Creates a `TextDocumentIdentifier` object for the current buffer. --- ---@param bufnr integer|nil: Buffer handle, defaults to current ----@returns `TextDocumentIdentifier` +---@return table `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params(bufnr) return { uri = vim.uri_from_bufnr(bufnr or 0) } end --- Create the workspace params ----@param added ----@param removed +---@param added table +---@param removed table function M.make_workspace_params(added, removed) return { event = { added = added, removed = removed } } end @@ -2137,7 +2144,7 @@ end --- ---@see 'shiftwidth' ---@param bufnr (integer|nil): Buffer handle, defaults to current ----@returns (integer) indentation size +---@return (integer) indentation size function M.get_effective_tabstop(bufnr) validate({ bufnr = { bufnr, 'n', true } }) local bo = bufnr and vim.bo[bufnr] or vim.bo @@ -2148,7 +2155,7 @@ end --- Creates a `DocumentFormattingParams` object for the current buffer and cursor position. --- ---@param options table|nil with valid `FormattingOptions` entries ----@returns `DocumentFormattingParams` object +---@return `DocumentFormattingParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting function M.make_formatting_params(options) validate({ options = { options, 't', true } }) @@ -2167,8 +2174,8 @@ end ---@param buf integer buffer number (0 for current) ---@param row 0-indexed line ---@param col 0-indexed byte offset in line ----@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of `buf` ----@returns (integer, integer) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} +---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf` +---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf} function M.character_offset(buf, row, col, offset_encoding) local line = get_line(buf, row) if offset_encoding == nil then @@ -2176,6 +2183,7 @@ function M.character_offset(buf, row, col, offset_encoding) 'character_offset must be called with valid offset encoding', vim.log.levels.WARN ) + offset_encoding = vim.lsp.get_active_clients({ bufnr = buf })[1].offset_encoding end -- If the col is past the EOL, use the line length. if col > #line then @@ -2186,11 +2194,11 @@ end --- Helper function to return nested values in language server settings --- ----@param settings a table of language server settings ----@param section a string indicating the field of the settings table ----@returns (table or string) The value of settings accessed via section +---@param settings table language server settings +---@param section string indicating the field of the settings table +---@return table|string The value of settings accessed via section function M.lookup_section(settings, section) - for part in vim.gsplit(section, '.', true) do + for part in vim.gsplit(section, '.', { plain = true }) do settings = settings[part] if settings == nil then return vim.NIL -- cgit From cf5f1492d702f940934b0b40024d1741e4474542 Mon Sep 17 00:00:00 2001 From: Raphael Date: Tue, 4 Jul 2023 20:30:31 +0800 Subject: fix(lsp): revert change to buf.clear_references() #24238 Problem: in #24046 the signature of buf.clear_references() changed, which indirectly breaks callers that were passing "ignored" args. Solution: because util.buf_clear_references() already defaulted to "current buffer", the change to buf.clear_references() isn't actually needed, so just revert it. --- runtime/lua/vim/lsp/buf.lua | 5 ++--- runtime/lua/vim/lsp/util.lua | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index c742505ec6..bac66b671d 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -581,9 +581,8 @@ function M.document_highlight() end --- Removes document highlights from current buffer. ---- @param bufnr integer|nil -function M.clear_references(bufnr) - util.buf_clear_references(bufnr or 0) +function M.clear_references() + util.buf_clear_references() end ---@private diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 6cb91417f2..8d6f88bb2c 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1769,9 +1769,9 @@ do --[[ References ]] --- Removes document highlights from a buffer. --- - ---@param bufnr integer Buffer id + ---@param bufnr integer|nil Buffer id function M.buf_clear_references(bufnr) - validate({ bufnr = { bufnr, { 'n', 'nil' }, true } }) + validate({ bufnr = { bufnr, { 'n' }, true } }) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) end -- cgit From af6e6ccf3dee815850639ec5613dda3442caa7d6 Mon Sep 17 00:00:00 2001 From: marshmallow Date: Sun, 30 Apr 2023 15:53:02 +1000 Subject: feat(vim.ui): vim.ui.open, "gx" without netrw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Mathias Fußenegger Co-authored-by: Justin M. Keyes Co-authored-by: ii14 <59243201+ii14@users.noreply.github.com> --- runtime/lua/vim/lsp/handlers.lua | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 625a2ed282..9b102c0f84 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -573,22 +573,15 @@ M['window/showDocument'] = function(_, result, ctx, _) if result.external then -- TODO(lvimuser): ask the user for confirmation - local cmd - if vim.fn.has('win32') == 1 then - cmd = { 'cmd.exe', '/c', 'start', '""', uri } - elseif vim.fn.has('macunix') == 1 then - cmd = { 'open', uri } - else - cmd = { 'xdg-open', uri } - end - local ret = vim.fn.system(cmd) - if vim.v.shell_error ~= 0 then + local ret = vim.ui.open(uri) + + if ret.code ~= 0 or ret == nil then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret, + message = ret and ret.stderr or 'No handler could be found', }, } end -- cgit From 67b2ed1004ae551c9fe1bbd29a86b5a301570800 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 2 Jul 2023 16:51:30 +0200 Subject: fix(gx): visual selection, expand env vars --- Rejected experiment: move vim.ui.open() to vim.env.open() Problem: `vim.ui` is where user-interface "providers" live, which can be overridden. It would also be useful to have a "providers" namespace for platform-specific features such as "open", clipboard, python, and the other providers listed in `:help providers`. We could overload `vim.ui` to serve that purpose as the single "providers" namespace, but `vim.ui.nodejs()` for example seems awkward. Solution: `vim.env` currently has too narrow of a purpose. Overload it to also be a namespace for `vim.env.open`. diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua index 913f1fe20348..17d05ff37595 100644 --- a/runtime/lua/vim/_meta.lua +++ b/runtime/lua/vim/_meta.lua @@ -37,8 +37,28 @@ local options_info = setmetatable({}, { end, }) -vim.env = setmetatable({}, { - __index = function(_, k) +vim.env = setmetatable({ + open = setmetatable({}, { + __call = function(_, uri) + print('xxxxx'..uri) + return true + end, + __tostring = function() + local v = vim.fn.getenv('open') + if v == vim.NIL then + return nil + end + return v + end, + }) + }, + { + __index = function(t, k, ...) + if k == 'open' then + error() + -- vim.print({...}) + -- return rawget(t, k) + end local v = vim.fn.getenv(k) if v == vim.NIL then return nil --- runtime/lua/vim/lsp/handlers.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 9b102c0f84..79d3f7aab0 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -576,12 +576,12 @@ M['window/showDocument'] = function(_, result, ctx, _) local ret = vim.ui.open(uri) - if ret.code ~= 0 or ret == nil then + if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret and ret.stderr or 'No handler could be found', + message = ret and ret.stderr or 'No handler found', }, } end @@ -593,7 +593,7 @@ M['window/showDocument'] = function(_, result, ctx, _) local client = vim.lsp.get_client_by_id(client_id) local client_name = client and client.name or string.format('id=%d', client_id) if not client then - err_message({ 'LSP[', client_name, '] client has shut down after sending ', ctx.method }) + err_message('LSP[', client_name, '] client has shut down after sending ', ctx.method) return vim.NIL end -- cgit From e644e7ce0b36dd5e75770f3faa0a84f15e2561e8 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Tue, 4 Jul 2023 23:33:23 +0200 Subject: fix(vim.ui.open): return (don't show) error message Problem: Showing an error via vim.notify() makes it awkward for callers such as lsp/handlers.lua to avoid showing redundant errors. Solution: Return the message instead of showing it. Let the caller decide whether and when to show the message. --- runtime/lua/vim/lsp/handlers.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 79d3f7aab0..70781cb7a6 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -573,15 +573,14 @@ M['window/showDocument'] = function(_, result, ctx, _) if result.external then -- TODO(lvimuser): ask the user for confirmation - - local ret = vim.ui.open(uri) + local ret, err = vim.ui.open(uri) if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret and ret.stderr or 'No handler found', + message = ret and ret.stderr or err, }, } end -- cgit From 21fa19f3e8c1d7b427c6d7c0dbcd6702d1e4e397 Mon Sep 17 00:00:00 2001 From: Chinmay Dalal Date: Sat, 8 Jul 2023 12:44:52 +0530 Subject: fix(lsp): don't use hl_mode = combine for inlay hints #24276 Problem: `hl_mode` for inlay hints is `combine`, causing bugs like inlay hints using highlights from the previous character (#24152, #24068) Solution: Don't use hl_mode=combine for inlay hints. --- runtime/lua/vim/lsp/inlay_hint.lua | 1 - 1 file changed, 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index f577a31696..6426b0c039 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -289,7 +289,6 @@ api.nvim_set_decoration_provider(namespace, { virt_text_pos = 'inline', ephemeral = false, virt_text = vt, - hl_mode = 'combine', }) end end -- cgit From 766f4978d6cb146511cf0b676c01e5327db46647 Mon Sep 17 00:00:00 2001 From: Raphael Date: Mon, 10 Jul 2023 19:38:15 +0800 Subject: fix(lint): lint warnings #24226 --- runtime/lua/vim/lsp/buf.lua | 15 ++++++++------- runtime/lua/vim/lsp/handlers.lua | 7 ++++--- runtime/lua/vim/lsp/log.lua | 2 +- runtime/lua/vim/lsp/rpc.lua | 17 ++++++++--------- runtime/lua/vim/lsp/sync.lua | 12 +++++++----- 5 files changed, 28 insertions(+), 25 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bac66b671d..8ae0e0cde3 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -13,10 +13,11 @@ local M = {} ---@param params (table|nil) Parameters to send to the server ---@param handler (function|nil) See |lsp-handler|. Follows |lsp-handler-resolution| -- ----@returns 2-tuple: ---- - Map of client-id:request-id pairs for all successful requests. ---- - Function which can be used to cancel all the requests. You could instead ---- iterate all clients and call their `cancel_request()` methods. +---@return table client_request_ids Map of client-id:request-id pairs +---for all successful requests. +---@return function _cancel_all_requests Function which can be used to +---cancel all the requests. You could instead +---iterate all clients and call their `cancel_request()` methods. --- ---@see |vim.lsp.buf_request()| local function request(method, params, handler) @@ -30,7 +31,7 @@ end --- Checks whether the language servers attached to the current buffer are --- ready. --- ----@returns `true` if server responds. +---@return boolean if server responds. ---@deprecated function M.server_ready() vim.deprecate('vim.lsp.buf.server_ready', nil, '0.10.0') @@ -108,7 +109,7 @@ end --- Retrieves the completion items at the current cursor position. Can only be --- called in Insert mode. --- ----@param context (context support not yet implemented) Additional information +---@param context table (context support not yet implemented) Additional information --- about the context in which a completion was triggered (how it was triggered, --- and by which trigger character, if applicable) --- @@ -549,7 +550,7 @@ end --- call, the user is prompted to enter a string on the command line. An empty --- string means no filtering is done. --- ----@param query (string, optional) +---@param query string|nil optional ---@param options table|nil additional options --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.workspace_symbol(query, options) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 70781cb7a6..20c4d7458b 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -382,7 +382,7 @@ M['textDocument/hover'] = M.hover ---@private --- Jumps to a location. Used as a handler for multiple LSP methods. ----@param _ (not used) +---@param _ nil not used ---@param result (table) result of LSP method; a location or a list of locations. ---@param ctx (table) table containing the context of the request, including the method ---(`textDocument/definition` can return `Location` or `Location[]` @@ -496,8 +496,9 @@ end --- Displays call hierarchy in the quickfix window. --- ---@param direction `"from"` for incoming calls and `"to"` for outgoing calls ----@returns `CallHierarchyIncomingCall[]` if {direction} is `"from"`, ----@returns `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, +---@return function +--- `CallHierarchyIncomingCall[]` if {direction} is `"from"`, +--- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, local make_call_hierarchy_handler = function(direction) return function(_, result) if not result then diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index c77e7c045b..033f93bd6e 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -44,7 +44,7 @@ do vim.fn.mkdir(vim.fn.stdpath('log'), 'p') --- Returns the log filename. - ---@returns (string) log filename + ---@return string log filename function log.get_filename() return logfilename end diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 6552eaa800..c110c3a67c 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -8,7 +8,7 @@ local is_win = uv.os_uname().version:find('Windows') ---@private --- Checks whether a given path exists and is a directory. ---@param filename (string) path to check ----@returns (bool) +---@return boolean local function is_dir(filename) local stat = uv.fs_stat(filename) return stat and stat.type == 'directory' or false @@ -18,7 +18,7 @@ end --- Embeds the given string into a table and correctly computes `Content-Length`. --- ---@param encoded_message (string) ----@returns (table) table containing encoded message and `Content-Length` attribute +---@return string containing encoded message and `Content-Length` attribute local function format_message_with_content_length(encoded_message) return table.concat({ 'Content-Length: ', @@ -32,7 +32,7 @@ end --- Parses an LSP Message's header --- ---@param header string: The header to parse. ----@return table parsed headers +---@return table # parsed headers local function parse_headers(header) assert(type(header) == 'string', 'header must be a string') local headers = {} @@ -190,7 +190,8 @@ end --- ---@param method (string) The invoked LSP method ---@param params (table): Parameters for the invoked LSP method ----@returns `nil` and `vim.lsp.protocol.ErrorCodes.MethodNotFound`. +---@return nil +---@return table `vim.lsp.protocol.ErrorCodes.MethodNotFound` function default_dispatchers.server_request(method, params) local _ = log.debug() and log.debug('server_request', method, params) return nil, rpc_response_error(protocol.ErrorCodes.MethodNotFound) @@ -268,7 +269,7 @@ end --- Sends a notification to the LSP server. ---@param method (string) The invoked LSP method ---@param params (any): Parameters for the invoked LSP method ----@returns (bool) `true` if notification could be sent, `false` if not +---@return boolean `true` if notification could be sent, `false` if not function Client:notify(method, params) return self:encode_and_send({ jsonrpc = '2.0', @@ -522,7 +523,7 @@ local function public_client(client) --- Sends a notification to the LSP server. ---@param method (string) The invoked LSP method ---@param params (table|nil): Parameters for the invoked LSP method - ---@returns (bool) `true` if notification could be sent, `false` if not + ---@return boolean `true` if notification could be sent, `false` if not function result.notify(method, params) return client:notify(method, params) end @@ -624,9 +625,7 @@ end --- server process. May contain: --- - {cwd} (string) Working directory for the LSP server process --- - {env} (table) Additional environment variables for LSP server process ----@returns Client RPC object. ---- ----@returns Methods: +---@return table|nil Client RPC object, with these methods: --- - `notify()` |vim.lsp.rpc.notify()| --- - `request()` |vim.lsp.rpc.request()| --- - `is_closing()` returns a boolean indicating if the RPC is closing. diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index fb5b0b3194..350c096b47 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -94,7 +94,8 @@ end ---@param line string the line to index into ---@param byte integer the byte idx ---@param offset_encoding string utf-8|utf-16|utf-32|nil (default: utf-8) ----@returns table byte_idx and char_idx of first change position +---@return integer byte_idx of first change position +---@return integer char_idx of first change position local function align_end_position(line, byte, offset_encoding) local char -- If on the first byte, or an empty string: the trivial case @@ -129,7 +130,7 @@ end ---@param lastline integer lastline from on_lines, adjusted to 1-index ---@param new_lastline integer new_lastline from on_lines, adjusted to 1-index ---@param offset_encoding string utf-8|utf-16|utf-32|nil (fallback to utf-8) ----@returns table line_idx, byte_idx, and char_idx of first change position +---@return table result table include line_idx, byte_idx, and char_idx of first change position local function compute_start_range( prev_lines, curr_lines, @@ -209,7 +210,8 @@ end ---@param lastline integer ---@param new_lastline integer ---@param offset_encoding string ----@returns (int, int) end_line_idx and end_col_idx of range +---@return integer|table end_line_idx and end_col_idx of range +---@return table|nil end_col_idx of range local function compute_end_range( prev_lines, curr_lines, @@ -310,7 +312,7 @@ end ---@param lines table list of lines ---@param start_range table table returned by first_difference ---@param end_range table new_end_range returned by last_difference ----@returns string text extracted from defined region +---@return string text extracted from defined region local function extract_text(lines, start_range, end_range, line_ending) if not lines[start_range.line_idx] then return '' @@ -392,7 +394,7 @@ end ---@param lastline integer line to begin search in old_lines for last difference ---@param new_lastline integer line to begin search in new_lines for last difference ---@param offset_encoding string encoding requested by language server ----@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent +---@return table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent function M.compute_diff( prev_lines, curr_lines, -- cgit From 317c80f460a7826421f40f57ee8bdbd736b0f225 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Wed, 12 Jul 2023 14:48:21 +0200 Subject: feat(lsp): add method filter to get_active_clients (#24319) --- runtime/lua/vim/lsp/buf.lua | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 8ae0e0cde3..b238b5c221 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -197,15 +197,6 @@ end function M.format(options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local clients = vim.lsp.get_active_clients({ - id = options.id, - bufnr = bufnr, - name = options.name, - }) - - if options.filter then - clients = vim.tbl_filter(options.filter, clients) - end local mode = api.nvim_get_mode().mode local range = options.range @@ -214,9 +205,15 @@ function M.format(options) end local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' - clients = vim.tbl_filter(function(client) - return client.supports_method(method) - end, clients) + local clients = vim.lsp.get_active_clients({ + id = options.id, + bufnr = bufnr, + name = options.name, + method = method, + }) + if options.filter then + clients = vim.tbl_filter(options.filter, clients) + end if #clients == 0 then vim.notify('[LSP] Format request failed, no matching language servers.') @@ -277,16 +274,13 @@ function M.rename(new_name, options) local clients = vim.lsp.get_active_clients({ bufnr = bufnr, name = options.name, + -- Clients must at least support rename, prepareRename is optional + method = 'textDocument/rename', }) if options.filter then clients = vim.tbl_filter(options.filter, clients) end - -- Clients must at least support rename, prepareRename is optional - clients = vim.tbl_filter(function(client) - return client.supports_method('textDocument/rename') - end, clients) - if #clients == 0 then vim.notify('[LSP] Rename, no matching language servers with rename capability.') end -- cgit From 2ecba65b4ba741618ecbfd2a50a939987078bc98 Mon Sep 17 00:00:00 2001 From: Techatrix <19954306+Techatrix@users.noreply.github.com> Date: Fri, 14 Jul 2023 05:36:10 +0000 Subject: fix(lsp): remove unknown LSP protocol property (#24345) 'hierarchicalWorkspaceSymbolSupport' is not part of the LSP Specification --- runtime/lua/vim/lsp/protocol.lua | 1 - 1 file changed, 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 27da891656..5bc0baf241 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -844,7 +844,6 @@ function protocol.make_client_capabilities() return res end)(), }, - hierarchicalWorkspaceSymbolSupport = true, }, configuration = true, workspaceFolders = true, -- cgit From 251ca45ac94851c896db0d27685622fb78a73b3e Mon Sep 17 00:00:00 2001 From: Mike <10135646+mikesmithgh@users.noreply.github.com> Date: Sun, 16 Jul 2023 06:11:45 -0400 Subject: fix(lsp): markdown code fence should allow space before info string #24364 Problem: Bash language server returns "hover" markdown content that starts with a code fence and info string of `man` preceded by whitespace, which Nvim does not render properly. See https://github.com/bash-lsp/bash-language-server/blob/0ee73c53cebdc18311d4a4ad9367185ea4d98a03/server/src/server.ts#L821C15-L821C15 ```typescript function getMarkdownContent(documentation: string, language?: string): LSP.MarkupContent { return { value: language ? // eslint-disable-next-line prefer-template ['``` ' + language, documentation, '```'].join('\n') : documentation, kind: LSP.MarkupKind.Markdown, } } ``` For example, ``` ``` man NAME git - the stupid content tracker ``` ``` If I remove the white space, then it is properly formatted. ``` ```man instead of ``` man ``` Per CommonMark Spec https://spec.commonmark.org/0.30/#info-string whitespace is allowed before and after the `info string` which identifies the language in a codeblock. > The line with the opening code fence may optionally contain some text > following the code fence; this is trimmed of leading and trailing > spaces or tabs and called the [info > string](https://spec.commonmark.org/0.30/#info-string). If the [info > string](https://spec.commonmark.org/0.30/#info-string) comes after > a backtick fence, it may not contain any backtick characters. (The > reason for this restriction is that otherwise some inline code would > be incorrectly interpreted as the beginning of a fenced code block.) Solution: Adjust stylize_markdown() to allow whitespace before codeblock info. --- runtime/lua/vim/lsp/util.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 8d6f88bb2c..0da88f800e 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1347,7 +1347,7 @@ function M.stylize_markdown(bufnr, contents, opts) -- table of fence types to {ft, begin, end} -- when ft is nil, we get the ft from the regex match local matchers = { - block = { nil, '```+([a-zA-Z0-9_]*)', '```+' }, + block = { nil, '```+%s*([a-zA-Z0-9_]*)', '```+' }, pre = { nil, '
([a-z0-9]*)', '
' }, code = { '', '', '' }, text = { 'text', '', '' }, -- cgit From 1b9ccd38a12f8fdbdff51ef0b3ff363540f745ec Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 17 Jul 2023 18:27:16 +0200 Subject: feat(lsp)!: rename vim.lsp.get_active_clients to get_clients (#24113) --- runtime/lua/vim/lsp/buf.lua | 11 +++++------ runtime/lua/vim/lsp/health.lua | 2 +- runtime/lua/vim/lsp/util.lua | 8 ++++---- 3 files changed, 10 insertions(+), 11 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index b238b5c221..2140d3ae37 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -197,7 +197,6 @@ end function M.format(options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local mode = api.nvim_get_mode().mode local range = options.range if not range and mode == 'v' or mode == 'V' then @@ -205,7 +204,7 @@ function M.format(options) end local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' - local clients = vim.lsp.get_active_clients({ + local clients = vim.lsp.get_clients({ id = options.id, bufnr = bufnr, name = options.name, @@ -271,7 +270,7 @@ end function M.rename(new_name, options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local clients = vim.lsp.get_active_clients({ + local clients = vim.lsp.get_clients({ bufnr = bufnr, name = options.name, -- Clients must at least support rename, prepareRename is optional @@ -468,7 +467,7 @@ end --- function M.list_workspace_folders() local workspace_folders = {} - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do for _, folder in pairs(client.workspace_folders or {}) do table.insert(workspace_folders, folder.name) end @@ -493,7 +492,7 @@ function M.add_workspace_folder(workspace_folder) { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } }, {} ) - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do local found = false for _, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then @@ -526,7 +525,7 @@ function M.remove_workspace_folder(workspace_folder) { {} }, { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } ) - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do for idx, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 8817bb71de..023b1c26be 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -28,7 +28,7 @@ function M.check() local report_fn = (log_size / 1000000 > 100 and report_warn or report_info) report_fn(string.format('Log size: %d KB', log_size / 1000)) - local clients = vim.lsp.get_active_clients() + local clients = vim.lsp.get_clients() vim.health.start('vim.lsp: Active Clients') if next(clients) then for _, client in pairs(clients) do diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 0da88f800e..59b9916f64 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -360,7 +360,7 @@ function M.get_progress_messages() local new_messages = {} local progress_remove = {} - for _, client in ipairs(vim.lsp.get_active_clients()) do + for _, client in ipairs(vim.lsp.get_clients()) do local groups = {} for progress in client.progress do local value = progress.value @@ -1841,7 +1841,7 @@ function M.locations_to_items(locations, offset_encoding) 'locations_to_items must be called with valid offset encoding', vim.log.levels.WARN ) - offset_encoding = vim.lsp.get_active_clients({ bufnr = 0 })[1].offset_encoding + offset_encoding = vim.lsp.get_clients({ bufnr = 0 })[1].offset_encoding end local items = {} @@ -2036,7 +2036,7 @@ function M._get_offset_encoding(bufnr) local offset_encoding - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = bufnr })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do if client.offset_encoding == nil then vim.notify_once( string.format( @@ -2183,7 +2183,7 @@ function M.character_offset(buf, row, col, offset_encoding) 'character_offset must be called with valid offset encoding', vim.log.levels.WARN ) - offset_encoding = vim.lsp.get_active_clients({ bufnr = buf })[1].offset_encoding + offset_encoding = vim.lsp.get_clients({ bufnr = buf })[1].offset_encoding end -- If the col is past the EOL, use the line length. if col > #line then -- cgit From be74807eef13ff8c90d55cf8b22b01d6d33b1641 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Tue, 18 Jul 2023 15:42:30 +0100 Subject: docs(lua): more improvements (#24387) * docs(lua): teach lua2dox how to table * docs(lua): teach gen_vimdoc.py about local functions No more need to mark local functions with @private * docs(lua): mention @nodoc and @meta in dev-lua-doc * fixup! Co-authored-by: Justin M. Keyes --------- Co-authored-by: Justin M. Keyes --- runtime/lua/vim/lsp/_watchfiles.lua | 1 - runtime/lua/vim/lsp/buf.lua | 14 ------- runtime/lua/vim/lsp/codelens.lua | 4 -- runtime/lua/vim/lsp/diagnostic.lua | 9 +---- runtime/lua/vim/lsp/handlers.lua | 3 -- runtime/lua/vim/lsp/inlay_hint.lua | 9 ----- runtime/lua/vim/lsp/log.lua | 17 +++------ runtime/lua/vim/lsp/rpc.lua | 68 +++++++++++++++------------------ runtime/lua/vim/lsp/semantic_tokens.lua | 7 ---- runtime/lua/vim/lsp/sync.lua | 7 ---- runtime/lua/vim/lsp/tagfunc.lua | 4 -- runtime/lua/vim/lsp/util.lua | 25 +----------- 12 files changed, 38 insertions(+), 130 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 87938fe4d5..b66f2f6f32 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -5,7 +5,6 @@ local lpeg = vim.lpeg local M = {} ----@private --- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" --- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. --- diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 2140d3ae37..46f582dc7e 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -5,7 +5,6 @@ local npcall = vim.F.npcall local M = {} ----@private --- Sends an async request to all active clients attached to the current --- buffer. --- @@ -45,7 +44,6 @@ function M.hover() request('textDocument/hover', params) end ----@private local function request_with_options(name, params, options) local req_handler if options then @@ -120,7 +118,6 @@ function M.completion(context) return request('textDocument/completion', params) end ----@private ---@param bufnr integer ---@param mode "v"|"V" ---@return table {start={row,col}, end={row,col}} using (1, 0) indexing @@ -218,7 +215,6 @@ function M.format(options) vim.notify('[LSP] Format request failed, no matching language servers.') end - ---@private local function set_range(client, params) if range then local range_params = @@ -289,7 +285,6 @@ function M.rename(new_name, options) -- Compute early to account for cursor movements after going async local cword = vim.fn.expand('') - ---@private local function get_text_at_range(range, offset_encoding) return api.nvim_buf_get_text( bufnr, @@ -307,7 +302,6 @@ function M.rename(new_name, options) return end - ---@private local function rename(name) local params = util.make_position_params(win, client.offset_encoding) params.newName = name @@ -408,7 +402,6 @@ function M.document_symbol(options) request_with_options('textDocument/documentSymbol', params, options) end ----@private local function pick_call_hierarchy_item(call_hierarchy_items) if not call_hierarchy_items then return @@ -428,7 +421,6 @@ local function pick_call_hierarchy_item(call_hierarchy_items) return choice end ----@private local function call_hierarchy(method) local params = util.make_position_params() request('textDocument/prepareCallHierarchy', params, function(err, result, ctx) @@ -579,8 +571,6 @@ function M.clear_references() util.buf_clear_references() end ----@private --- --- This is not public because the main extension point is --- vim.ui.select which can be overridden independently. --- @@ -592,7 +582,6 @@ end local function on_code_action_results(results, ctx, options) local action_tuples = {} - ---@private local function action_filter(a) -- filter by specified action kind if options and options.context and options.context.only then @@ -632,7 +621,6 @@ local function on_code_action_results(results, ctx, options) return end - ---@private local function apply_action(action, client) if action.edit then util.apply_workspace_edit(action.edit, client.offset_encoding) @@ -643,7 +631,6 @@ local function on_code_action_results(results, ctx, options) end end - ---@private local function on_user_choice(action_tuple) if not action_tuple then return @@ -701,7 +688,6 @@ end --- Requests code actions from all clients and calls the handler exactly once --- with all aggregated results ----@private local function code_action_request(params, options) local bufnr = api.nvim_get_current_buf() local method = 'textDocument/codeAction' diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 67104cc40b..a516238ae0 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -26,7 +26,6 @@ local namespaces = setmetatable({}, { ---@private M.__namespaces = namespaces ----@private local function execute_lens(lens, bufnr, client_id) local line = lens.range.start.line api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) @@ -89,7 +88,6 @@ function M.run() end end ----@private local function resolve_bufnr(bufnr) return bufnr == 0 and api.nvim_get_current_buf() or bufnr end @@ -186,7 +184,6 @@ function M.save(lenses, bufnr, client_id) lenses_by_client[client_id] = lenses end ----@private local function resolve_lenses(lenses, bufnr, client_id, callback) lenses = lenses or {} local num_lens = vim.tbl_count(lenses) @@ -195,7 +192,6 @@ local function resolve_lenses(lenses, bufnr, client_id, callback) return end - ---@private local function countdown() num_lens = num_lens - 1 if num_lens == 0 then diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 3efa5c51ff..c2cf7c6ba5 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -5,7 +5,7 @@ local protocol = require('vim.lsp.protocol') local M = {} local DEFAULT_CLIENT_ID = -1 ----@private + local function get_client_id(client_id) if client_id == nil then client_id = DEFAULT_CLIENT_ID @@ -14,7 +14,6 @@ local function get_client_id(client_id) return client_id end ----@private ---@param severity lsp.DiagnosticSeverity local function severity_lsp_to_vim(severity) if type(severity) == 'string' then @@ -23,7 +22,6 @@ local function severity_lsp_to_vim(severity) return severity end ----@private ---@return lsp.DiagnosticSeverity local function severity_vim_to_lsp(severity) if type(severity) == 'string' then @@ -32,7 +30,6 @@ local function severity_vim_to_lsp(severity) return severity end ----@private ---@return integer local function line_byte_from_position(lines, lnum, col, offset_encoding) if not lines or offset_encoding == 'utf-8' then @@ -48,7 +45,6 @@ local function line_byte_from_position(lines, lnum, col, offset_encoding) return col end ----@private local function get_buf_lines(bufnr) if vim.api.nvim_buf_is_loaded(bufnr) then return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) @@ -73,7 +69,6 @@ local function get_buf_lines(bufnr) return lines end ---- @private --- @param diagnostic lsp.Diagnostic --- @param client_id integer --- @return table? @@ -96,7 +91,6 @@ local function tags_lsp_to_vim(diagnostic, client_id) return tags end ----@private ---@param diagnostics lsp.Diagnostic[] ---@param bufnr integer ---@param client_id integer @@ -133,7 +127,6 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) end, diagnostics) end ---- @private --- @param diagnostics Diagnostic[] --- @return lsp.Diagnostic[] local function diagnostic_vim_to_lsp(diagnostics) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 20c4d7458b..ce3db68618 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -7,7 +7,6 @@ local M = {} -- FIXME: DOC: Expose in vimdocs ----@private --- Writes to error buffer. ---@param ... string Will be concatenated before being written local function err_message(...) @@ -246,7 +245,6 @@ M['textDocument/references'] = function(_, result, ctx, config) end end ----@private --- Return a function that converts LSP responses to list items and opens the list --- --- The returned function has an optional {config} parameter that accepts a table @@ -380,7 +378,6 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover M['textDocument/hover'] = M.hover ----@private --- Jumps to a location. Used as a handler for multiple LSP methods. ---@param _ nil not used ---@param result (table) result of LSP method; a location or a list of locations. diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 6426b0c039..bec6f33e93 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -17,7 +17,6 @@ local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) --- Reset the request debounce timer of a buffer ----@private local function reset_timer(reset_bufnr) local timer = bufstates[reset_bufnr].timer if timer then @@ -63,7 +62,6 @@ function M.on_inlayhint(err, result, ctx, _) end local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) - ---@private local function pos_to_byte(position) local col = position.character if col > 0 then @@ -89,7 +87,6 @@ function M.on_inlayhint(err, result, ctx, _) api.nvim__buf_redraw_range(bufnr, 0, -1) end ----@private local function resolve_bufnr(bufnr) return bufnr > 0 and bufnr or api.nvim_get_current_buf() end @@ -100,7 +97,6 @@ end --- - bufnr (integer, default: 0): Buffer whose hints to refresh --- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer --- ----@private local function refresh(opts) opts = opts or {} local bufnr = resolve_bufnr(opts.bufnr or 0) @@ -159,7 +155,6 @@ end --- Clear inlay hints ---@param bufnr (integer) Buffer handle, or 0 for current ----@private local function clear(bufnr) bufnr = resolve_bufnr(bufnr) if not bufstates[bufnr] then @@ -178,7 +173,6 @@ local function clear(bufnr) api.nvim__buf_redraw_range(bufnr, 0, -1) end ----@private local function make_request(request_bufnr) reset_timer(request_bufnr) refresh({ bufnr = request_bufnr }) @@ -186,7 +180,6 @@ end --- Enable inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current ----@private local function enable(bufnr) bufnr = resolve_bufnr(bufnr) local bufstate = bufstates[bufnr] @@ -228,7 +221,6 @@ end --- Disable inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current ----@private local function disable(bufnr) bufnr = resolve_bufnr(bufnr) if bufstates[bufnr] and bufstates[bufnr].enabled then @@ -240,7 +232,6 @@ end --- Toggle inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current ----@private local function toggle(bufnr) bufnr = resolve_bufnr(bufnr) local bufstate = bufstates[bufnr] diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index 033f93bd6e..6d2e0bc292 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -2,14 +2,12 @@ local log = {} --- FIXME: DOC --- Should be exposed in the vim docs. --- --- Log level dictionary with reverse lookup as well. --- --- Can be used to lookup the number from the name or the name from the number. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" --- Level numbers begin with "TRACE" at 0 +--- Log level dictionary with reverse lookup as well. +--- +--- Can be used to lookup the number from the name or the name from the number. +--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" +--- Level numbers begin with "TRACE" at 0 +--- @nodoc log.levels = vim.deepcopy(vim.log.levels) -- Default log level is warn. @@ -20,7 +18,6 @@ local format_func = function(arg) end do - ---@private local function notify(msg, level) if vim.in_fast_event() then vim.schedule(function() @@ -32,7 +29,6 @@ do end local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/' - ---@private local function path_join(...) return table.concat(vim.tbl_flatten({ ... }), path_sep) end @@ -50,7 +46,6 @@ do end local logfile, openerr - ---@private --- Opens log file. Returns true if file is open, false on error local function open_logfile() -- Try to open file only once diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index c110c3a67c..a77af937b3 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -5,7 +5,6 @@ local validate, schedule, schedule_wrap = vim.validate, vim.schedule, vim.schedu local is_win = uv.os_uname().version:find('Windows') ----@private --- Checks whether a given path exists and is a directory. ---@param filename (string) path to check ---@return boolean @@ -14,7 +13,6 @@ local function is_dir(filename) return stat and stat.type == 'directory' or false end ----@private --- Embeds the given string into a table and correctly computes `Content-Length`. --- ---@param encoded_message (string) @@ -28,7 +26,6 @@ local function format_message_with_content_length(encoded_message) }) end ----@private --- Parses an LSP Message's header --- ---@param header string: The header to parse. @@ -60,7 +57,6 @@ local header_start_pattern = ('content'):gsub('%w', function(c) return '[' .. c .. c:upper() .. ']' end) ----@private --- The actual workhorse. local function request_parser_loop() local buffer = '' -- only for header part @@ -115,8 +111,11 @@ local function request_parser_loop() end end +local M = {} + --- Mapping of error codes used by the client -local client_errors = { +--- @nodoc +M.client_errors = { INVALID_SERVER_MESSAGE = 1, INVALID_SERVER_JSON = 2, NO_RESULT_CALLBACK_FOUND = 3, @@ -126,13 +125,13 @@ local client_errors = { SERVER_RESULT_CALLBACK_ERROR = 7, } -client_errors = vim.tbl_add_reverse_lookup(client_errors) +M.client_errors = vim.tbl_add_reverse_lookup(M.client_errors) --- Constructs an error message from an LSP error object. --- ---@param err (table) The error object ---@returns (string) The formatted error message -local function format_rpc_error(err) +function M.format_rpc_error(err) validate({ err = { err, 't' }, }) @@ -163,7 +162,7 @@ end ---@param code integer RPC error code defined in `vim.lsp.protocol.ErrorCodes` ---@param message string|nil arbitrary message to send to server ---@param data any|nil arbitrary data to send to server -local function rpc_response_error(code, message, data) +function M.rpc_response_error(code, message, data) -- TODO should this error or just pick a sane error (like InternalError)? local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code') return setmetatable({ @@ -171,7 +170,7 @@ local function rpc_response_error(code, message, data) message = message or code_name, data = data, }, { - __tostring = format_rpc_error, + __tostring = M.format_rpc_error, }) end @@ -185,6 +184,7 @@ local default_dispatchers = {} function default_dispatchers.notification(method, params) local _ = log.debug() and log.debug('notification', method, params) end + ---@private --- Default dispatcher for requests sent to an LSP server. --- @@ -194,8 +194,9 @@ end ---@return table `vim.lsp.protocol.ErrorCodes.MethodNotFound` function default_dispatchers.server_request(method, params) local _ = log.debug() and log.debug('server_request', method, params) - return nil, rpc_response_error(protocol.ErrorCodes.MethodNotFound) + return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound) end + ---@private --- Default dispatcher for when a client exits. --- @@ -205,6 +206,7 @@ end function default_dispatchers.on_exit(code, signal) local _ = log.info() and log.info('client_exit', { code = code, signal = signal }) end + ---@private --- Default dispatcher for client errors. --- @@ -212,11 +214,11 @@ end ---@param err (any): Details about the error ---any) function default_dispatchers.on_error(code, err) - local _ = log.error() and log.error('client_error:', client_errors[code], err) + local _ = log.error() and log.error('client_error:', M.client_errors[code], err) end ---@private -local function create_read_loop(handle_body, on_no_chunk, on_error) +function M.create_read_loop(handle_body, on_no_chunk, on_error) local parse_chunk = coroutine.wrap(request_parser_loop) parse_chunk() return function(err, chunk) @@ -329,7 +331,7 @@ end ---@private function Client:on_error(errkind, ...) - assert(client_errors[errkind]) + assert(M.client_errors[errkind]) -- TODO what to do if this fails? pcall(self.dispatchers.on_error, errkind, ...) end @@ -356,7 +358,7 @@ end function Client:handle_body(body) local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) if not ok then - self:on_error(client_errors.INVALID_SERVER_JSON, decoded) + self:on_error(M.client_errors.INVALID_SERVER_JSON, decoded) return end local _ = log.debug() and log.debug('rpc.receive', decoded) @@ -369,7 +371,7 @@ function Client:handle_body(body) coroutine.wrap(function() local status, result status, result, err = self:try_call( - client_errors.SERVER_REQUEST_HANDLER_ERROR, + M.client_errors.SERVER_REQUEST_HANDLER_ERROR, self.dispatchers.server_request, decoded.method, decoded.params @@ -401,7 +403,7 @@ function Client:handle_body(body) end else -- On an exception, result will contain the error message. - err = rpc_response_error(protocol.ErrorCodes.InternalError, result) + err = M.rpc_response_error(protocol.ErrorCodes.InternalError, result) result = nil end self:send_response(decoded.id, err, result) @@ -454,34 +456,33 @@ function Client:handle_body(body) }) if decoded.error then decoded.error = setmetatable(decoded.error, { - __tostring = format_rpc_error, + __tostring = M.format_rpc_error, }) end self:try_call( - client_errors.SERVER_RESULT_CALLBACK_ERROR, + M.client_errors.SERVER_RESULT_CALLBACK_ERROR, callback, decoded.error, decoded.result ) else - self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) + self:on_error(M.client_errors.NO_RESULT_CALLBACK_FOUND, decoded) local _ = log.error() and log.error('No callback found for server response id ' .. result_id) end elseif type(decoded.method) == 'string' then -- Notification self:try_call( - client_errors.NOTIFICATION_HANDLER_ERROR, + M.client_errors.NOTIFICATION_HANDLER_ERROR, self.dispatchers.notification, decoded.method, decoded.params ) else -- Invalid server message - self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) + self:on_error(M.client_errors.INVALID_SERVER_MESSAGE, decoded) end end ----@private ---@return RpcClient local function new_client(dispatchers, transport) local state = { @@ -494,7 +495,6 @@ local function new_client(dispatchers, transport) return setmetatable(state, { __index = Client }) end ----@private ---@param client RpcClient local function public_client(client) local result = {} @@ -531,7 +531,6 @@ local function public_client(client) return result end ----@private local function merge_dispatchers(dispatchers) if dispatchers then local user_dispatchers = dispatchers @@ -565,7 +564,7 @@ end ---@param host string ---@param port integer ---@return function -local function connect(host, port) +function M.connect(host, port) return function(dispatchers) dispatchers = merge_dispatchers(dispatchers) local tcp = uv.new_tcp() @@ -600,8 +599,8 @@ local function connect(host, port) local handle_body = function(body) client:handle_body(body) end - tcp:read_start(create_read_loop(handle_body, transport.terminate, function(read_err) - client:on_error(client_errors.READ_ERROR, read_err) + tcp:read_start(M.create_read_loop(handle_body, transport.terminate, function(read_err) + client:on_error(M.client_errors.READ_ERROR, read_err) end)) end) @@ -630,7 +629,7 @@ end --- - `request()` |vim.lsp.rpc.request()| --- - `is_closing()` returns a boolean indicating if the RPC is closing. --- - `terminate()` terminates the RPC client. -local function start(cmd, cmd_args, dispatchers, extra_spawn_params) +function M.start(cmd, cmd_args, dispatchers, extra_spawn_params) if log.info() then log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) end @@ -667,8 +666,8 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) client:handle_body(body) end - local stdout_handler = create_read_loop(handle_body, nil, function(err) - client:on_error(client_errors.READ_ERROR, err) + local stdout_handler = M.create_read_loop(handle_body, nil, function(err) + client:on_error(M.client_errors.READ_ERROR, err) end) local stderr_handler = function(_, chunk) @@ -714,11 +713,4 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) return public_client(client) end -return { - start = start, - connect = connect, - rpc_response_error = rpc_response_error, - format_rpc_error = format_rpc_error, - client_errors = client_errors, - create_read_loop = create_read_loop, -} +return M diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 191cc7b400..84723bbc05 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -41,8 +41,6 @@ local STHighlighter = { active = {} } --- --- Return the index i in range such that tokens[j].line < line for all j < i, and --- tokens[j].line >= line for all j >= i, or return hi if no such index is found. ---- ----@private local function lower_bound(tokens, line, lo, hi) while lo < hi do local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). @@ -59,8 +57,6 @@ end --- --- Return the index i in range such that tokens[j].line <= line for all j < i, and --- tokens[j].line > line for all j >= i, or return hi if no such index is found. ---- ----@private local function upper_bound(tokens, line, lo, hi) while lo < hi do local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). @@ -75,7 +71,6 @@ end --- Extracts modifier strings from the encoded number in the token array --- ----@private ---@return table local function modifiers_from_number(x, modifiers_table) local modifiers = {} @@ -93,7 +88,6 @@ end --- Converts a raw token list to a list of highlight ranges used by the on_win callback --- ----@private ---@return STTokenRange[] local function tokens_to_ranges(data, bufnr, client, request) local legend = client.server_capabilities.semanticTokensProvider.legend @@ -137,7 +131,6 @@ local function tokens_to_ranges(data, bufnr, client, request) local token_type = token_types[data[i + 3] + 1] local modifiers = modifiers_from_number(data[i + 4], token_modifiers) - ---@private local function _get_byte_pos(col) if col > 0 then local buf_line = lines[line + 1] or '' diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index 350c096b47..9c1bbf3892 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -48,7 +48,6 @@ local str_utfindex = vim.str_utfindex local str_utf_start = vim.str_utf_start local str_utf_end = vim.str_utf_end ----@private -- Given a line, byte idx, and offset_encoding convert to the -- utf-8, utf-16, or utf-32 index. ---@param line string the line to index into @@ -74,7 +73,6 @@ local function byte_to_utf(line, byte, offset_encoding) return utf_idx + 1 end ----@private local function compute_line_length(line, offset_encoding) local length local _ @@ -88,7 +86,6 @@ local function compute_line_length(line, offset_encoding) return length end ----@private -- Given a line, byte idx, alignment, and offset_encoding convert to the aligned -- utf-8 index and either the utf-16, or utf-32 index. ---@param line string the line to index into @@ -122,7 +119,6 @@ local function align_end_position(line, byte, offset_encoding) return byte, char end ----@private --- Finds the first line, byte, and char index of the difference between the previous and current lines buffer normalized to the previous codepoint. ---@param prev_lines table list of lines from previous buffer ---@param curr_lines table list of lines from current buffer @@ -198,7 +194,6 @@ local function compute_start_range( return { line_idx = firstline, byte_idx = byte_idx, char_idx = char_idx } end ----@private --- Finds the last line and byte index of the differences between prev and current buffer. --- Normalized to the next codepoint. --- prev_end_range is the text range sent to the server representing the changed region. @@ -307,7 +302,6 @@ local function compute_end_range( return prev_end_range, curr_end_range end ----@private --- Get the text of the range defined by start and end line/column ---@param lines table list of lines ---@param start_range table table returned by first_difference @@ -343,7 +337,6 @@ local function extract_text(lines, start_range, end_range, line_ending) end end ----@private -- rangelength depends on the offset encoding -- bytes for utf-8 (clangd with extension) -- codepoints for utf-16 diff --git a/runtime/lua/vim/lsp/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index eb25b67db9..c70eb573c2 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -1,7 +1,6 @@ local lsp = vim.lsp local util = lsp.util ----@private local function mk_tag_item(name, range, uri, offset_encoding) local bufnr = vim.uri_to_bufnr(uri) -- This is get_line_byte_from_position is 0-indexed, call cursor expects a 1-indexed position @@ -13,7 +12,6 @@ local function mk_tag_item(name, range, uri, offset_encoding) } end ----@private local function query_definition(pattern) local params = util.make_position_params() local results_by_client, err = lsp.buf_request_sync(0, 'textDocument/definition', params, 1000) @@ -42,7 +40,6 @@ local function query_definition(pattern) return results end ----@private local function query_workspace_symbols(pattern) local results_by_client, err = lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000) @@ -62,7 +59,6 @@ local function query_workspace_symbols(pattern) return results end ----@private local function tagfunc(pattern, flags) local matches if string.match(flags, 'c') then diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 59b9916f64..9a6114c35b 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -22,7 +22,6 @@ local default_border = { { ' ', 'NormalFloat' }, } ----@private --- Check the border given by opts or the default border for the additional --- size it adds to a float. ---@param opts table optional options for the floating window @@ -60,7 +59,6 @@ local function get_border_size(opts) ) ) end - ---@private local function border_width(id) id = (id - 1) % #border + 1 if type(border[id]) == 'table' then @@ -77,7 +75,6 @@ local function get_border_size(opts) ) ) end - ---@private local function border_height(id) id = (id - 1) % #border + 1 if type(border[id]) == 'table' then @@ -103,13 +100,11 @@ local function get_border_size(opts) return { height = height, width = width } end ----@private local function split_lines(value) value = string.gsub(value, '\r\n?', '\n') return split(value, '\n', { plain = true }) end ----@private local function create_window_without_focus() local prev = vim.api.nvim_get_current_win() vim.cmd.new() @@ -219,7 +214,6 @@ function M.set_lines(lines, A, B, new_lines) return lines end ----@private local function sort_by_key(fn) return function(a, b) local ka, kb = fn(a), fn(b) @@ -234,7 +228,6 @@ local function sort_by_key(fn) end end ----@private --- Gets the zero-indexed lines from the given buffer. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. @@ -250,7 +243,6 @@ local function get_lines(bufnr, rows) bufnr = api.nvim_get_current_buf() end - ---@private local function buf_lines() local lines = {} for _, row in ipairs(rows) do @@ -316,7 +308,6 @@ local function get_lines(bufnr, rows) return lines end ----@private --- Gets the zero-indexed line from the given buffer. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. @@ -328,7 +319,6 @@ local function get_line(bufnr, row) return get_lines(bufnr, { row })[row] end ----@private --- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position --- Returns a zero-indexed column, since set_lines() does the conversion to ---@param offset_encoding string|nil utf-8|utf-16|utf-32 @@ -670,7 +660,6 @@ function M.parse_snippet(input) return parsed end ----@private --- Sorts by CompletionItem.sortText. --- --see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion @@ -680,7 +669,6 @@ local function sort_completion_items(items) end) end ----@private --- Returns text that should be inserted when selecting completion item. The --- precedence is as follows: textEdit.newText > insertText > label --see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion @@ -703,7 +691,6 @@ local function get_completion_word(item) return item.label end ----@private --- Some language servers return complementary candidates whose prefixes do not --- match are also returned. So we exclude completion candidates whose prefix --- does not match. @@ -784,7 +771,6 @@ function M.text_document_completion_list_to_complete_items(result, prefix) return matches end ----@private --- Like vim.fn.bufwinid except it works across tabpages. local function bufwinid(bufnr) for _, win in ipairs(api.nvim_list_wins()) do @@ -795,7 +781,6 @@ local function bufwinid(bufnr) end --- Get list of buffers for a directory ----@private local function get_dir_bufs(path) path = path:gsub('([^%w])', '%%%1') local buffers = {} @@ -855,7 +840,6 @@ function M.rename(old_fname, new_fname, opts) end end ----@private local function create_file(change) local opts = change.options or {} -- from spec: Overwrite wins over `ignoreIfExists` @@ -870,7 +854,6 @@ local function create_file(change) vim.fn.bufadd(fname) end ----@private local function delete_file(change) local opts = change.options or {} local fname = vim.uri_to_fname(change.uri) @@ -1266,7 +1249,6 @@ function M.preview_location(location, opts) return M.open_floating_preview(contents, syntax, opts) end ----@private local function find_window_by_var(name, value) for _, win in ipairs(api.nvim_list_wins()) do if npcall(api.nvim_win_get_var, win, name) == value then @@ -1305,7 +1287,6 @@ end --- Generates a table mapping markdown code block lang to vim syntax, --- based on g:markdown_fenced_languages ---@return table table of lang -> syntax mappings ----@private local function get_markdown_fences() local fences = {} for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do @@ -1460,7 +1441,6 @@ function M.stylize_markdown(bufnr, contents, opts) api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped) local idx = 1 - ---@private -- keep track of syntaxes we already included. -- no need to include the same syntax more than once local langs = {} @@ -1521,7 +1501,6 @@ function M.stylize_markdown(bufnr, contents, opts) return stripped end ----@private --- Closes the preview window --- ---@param winnr integer window id of preview window @@ -1539,7 +1518,6 @@ local function close_preview_window(winnr, bufnrs) end) end ----@private --- Creates autocommands to close a preview window when events happen. --- ---@param events table list of events @@ -1905,7 +1883,6 @@ end --- ---@param symbols table DocumentSymbol[] or SymbolInformation[] function M.symbols_to_items(symbols, bufnr) - ---@private local function _symbols_to_items(_symbols, _items, _bufnr) for _, symbol in ipairs(_symbols) do if symbol.location then -- SymbolInformation type @@ -1991,7 +1968,6 @@ function M.try_trim_markdown_code_blocks(lines) return 'markdown' end ----@private ---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` local function make_position_param(window, offset_encoding) @@ -2209,6 +2185,7 @@ end M._get_line_byte_from_position = get_line_byte_from_position +---@nodoc M.buf_versions = {} return M -- cgit From 63b3408551561127f7845470eb51404bcd6f547b Mon Sep 17 00:00:00 2001 From: Chris AtLee Date: Thu, 20 Jul 2023 03:03:48 -0400 Subject: feat(lsp): implement textDocument/diagnostic (#24128) --- runtime/lua/vim/lsp/diagnostic.lua | 187 ++++++++++++++++++++++++++++++++++--- runtime/lua/vim/lsp/handlers.lua | 4 + runtime/lua/vim/lsp/inlay_hint.lua | 77 ++++----------- runtime/lua/vim/lsp/protocol.lua | 3 + runtime/lua/vim/lsp/util.lua | 40 ++++++++ 5 files changed, 242 insertions(+), 69 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index c2cf7c6ba5..34be13096d 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -1,9 +1,14 @@ ---@brief lsp-diagnostic +local util = require('vim.lsp.util') local protocol = require('vim.lsp.protocol') +local api = vim.api + local M = {} +local augroup = api.nvim_create_augroup('vim_lsp_diagnostic', {}) + local DEFAULT_CLIENT_ID = -1 local function get_client_id(client_id) @@ -154,19 +159,43 @@ local function diagnostic_vim_to_lsp(diagnostics) end ---@type table -local _client_namespaces = {} +local _client_push_namespaces = {} +---@type table +local _client_pull_namespaces = {} ---- Get the diagnostic namespace associated with an LSP client |vim.diagnostic|. +--- Get the diagnostic namespace associated with an LSP client |vim.diagnostic| for diagnostics --- ---@param client_id integer The id of the LSP client -function M.get_namespace(client_id) +---@param is_pull boolean Whether the namespace is for a pull or push client +function M.get_namespace(client_id, is_pull) vim.validate({ client_id = { client_id, 'n' } }) - if not _client_namespaces[client_id] then - local client = vim.lsp.get_client_by_id(client_id) - local name = string.format('vim.lsp.%s.%d', client and client.name or 'unknown', client_id) - _client_namespaces[client_id] = vim.api.nvim_create_namespace(name) + + local namespace_table + local key + local name + local client = vim.lsp.get_client_by_id(client_id) + + if is_pull then + namespace_table = _client_pull_namespaces + local server_id = vim.tbl_get(client.server_capabilities, 'diagnosticProvider', 'identifier') + key = string.format('%d:%s', client_id, server_id or 'nil') + name = string.format( + 'vim.lsp.%s.%d.%s', + client and client.name or 'unknown', + client_id, + server_id or 'nil' + ) + else + namespace_table = _client_push_namespaces + key = client_id + name = string.format('vim.lsp.%s.%d', client and client.name or 'unknown', client_id) end - return _client_namespaces[client_id] + + if not namespace_table[key] then + namespace_table[key] = api.nvim_create_namespace(name) + end + + return namespace_table[key] end --- |lsp-handler| for the method "textDocument/publishDiagnostics" @@ -209,7 +238,7 @@ function M.on_publish_diagnostics(_, result, ctx, config) end client_id = get_client_id(client_id) - local namespace = M.get_namespace(client_id) + local namespace = M.get_namespace(client_id, false) if config then for _, opt in pairs(config) do @@ -229,7 +258,75 @@ function M.on_publish_diagnostics(_, result, ctx, config) vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)) end ---- Clear diagnostics and diagnostic cache. +--- |lsp-handler| for the method "textDocument/diagnostic" +--- +--- See |vim.diagnostic.config()| for configuration options. Handler-specific +--- configuration can be set using |vim.lsp.with()|: +---
lua
+--- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with(
+---   vim.lsp.diagnostic.on_diagnostic, {
+---     -- Enable underline, use default values
+---     underline = true,
+---     -- Enable virtual text, override spacing to 4
+---     virtual_text = {
+---       spacing = 4,
+---     },
+---     -- Use a function to dynamically turn signs off
+---     -- and on, using buffer local variables
+---     signs = function(namespace, bufnr)
+---       return vim.b[bufnr].show_signs == true
+---     end,
+---     -- Disable a feature
+---     update_in_insert = false,
+---   }
+--- )
+--- 
+--- +---@param config table Configuration table (see |vim.diagnostic.config()|). +function M.on_diagnostic(_, result, ctx, config) + local client_id = ctx.client_id + local uri = ctx.params.textDocument.uri + local fname = vim.uri_to_fname(uri) + + if result == nil then + return + end + + if result.kind == 'unchanged' then + return + end + + local diagnostics = result.items + if #diagnostics == 0 and vim.fn.bufexists(fname) == 0 then + return + end + local bufnr = vim.fn.bufadd(fname) + + if not bufnr then + return + end + + client_id = get_client_id(client_id) + + local namespace = M.get_namespace(client_id, true) + + if config then + for _, opt in pairs(config) do + if type(opt) == 'table' and not opt.severity and opt.severity_limit then + opt.severity = { min = severity_lsp_to_vim(opt.severity_limit) } + end + end + + -- Persist configuration to ensure buffer reloads use the same + -- configuration. To make lsp.with configuration work (See :help + -- lsp-handler-configuration) + vim.diagnostic.config(config, namespace) + end + + vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)) +end + +--- Clear push diagnostics and diagnostic cache. --- --- Diagnostic producers should prefer |vim.diagnostic.reset()|. However, --- this method signature is still used internally in some parts of the LSP @@ -243,7 +340,7 @@ function M.reset(client_id, buffer_client_map) vim.schedule(function() for bufnr, client_ids in pairs(buffer_client_map) do if client_ids[client_id] then - local namespace = M.get_namespace(client_id) + local namespace = M.get_namespace(client_id, false) vim.diagnostic.reset(namespace, bufnr) end end @@ -275,7 +372,7 @@ function M.get_line_diagnostics(bufnr, line_nr, opts, client_id) end if client_id then - opts.namespace = M.get_namespace(client_id) + opts.namespace = M.get_namespace(client_id, false) end if not line_nr then @@ -287,4 +384,70 @@ function M.get_line_diagnostics(bufnr, line_nr, opts, client_id) return diagnostic_vim_to_lsp(vim.diagnostic.get(bufnr, opts)) end +--- Clear diagnostics from pull based clients +--- @private +local function clear(bufnr) + for _, namespace in pairs(_client_pull_namespaces) do + vim.diagnostic.reset(namespace, bufnr) + end +end + +--- autocmd ids for LspNotify handlers per buffer +--- @private +--- @type table +local _autocmd_ids = {} + +--- Disable pull diagnostics for a buffer +--- @private +local function disable(bufnr) + if not _autocmd_ids[bufnr] then + return + end + api.nvim_del_autocmd(_autocmd_ids[bufnr]) + _autocmd_ids[bufnr] = nil + clear(bufnr) +end + +--- Enable pull diagnostics for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +function M._enable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + if _autocmd_ids[bufnr] then + return + end + + _autocmd_ids[bufnr] = api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if opts.data.method ~= 'textDocument/didChange' then + return + end + util._refresh('textDocument/diagnostic', { bufnr = bufnr, only_visible = true }) + end, + group = augroup, + }) + + api.nvim_buf_attach(bufnr, false, { + on_reload = function() + util._refresh('textDocument/diagnostic', { bufnr = bufnr }) + end, + on_detach = function() + disable(bufnr) + end, + }) + + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function() + disable(bufnr) + end, + once = true, + group = augroup, + }) +end + return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index ce3db68618..d887183972 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -214,6 +214,10 @@ M['textDocument/publishDiagnostics'] = function(...) return require('vim.lsp.diagnostic').on_publish_diagnostics(...) end +M['textDocument/diagnostic'] = function(...) + return require('vim.lsp.diagnostic').on_diagnostic(...) +end + M['textDocument/codeLens'] = function(...) return require('vim.lsp.codelens').on_codelens(...) end diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index bec6f33e93..1c29e8a866 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -87,54 +87,6 @@ function M.on_inlayhint(err, result, ctx, _) api.nvim__buf_redraw_range(bufnr, 0, -1) end -local function resolve_bufnr(bufnr) - return bufnr > 0 and bufnr or api.nvim_get_current_buf() -end - ---- Refresh inlay hints for a buffer ---- ----@param opts (nil|table) Optional arguments ---- - bufnr (integer, default: 0): Buffer whose hints to refresh ---- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer ---- -local function refresh(opts) - opts = opts or {} - local bufnr = resolve_bufnr(opts.bufnr or 0) - local bufstate = bufstates[bufnr] - if not (bufstate and bufstate.enabled) then - return - end - local only_visible = opts.only_visible or false - local buffer_windows = {} - for _, winid in ipairs(api.nvim_list_wins()) do - if api.nvim_win_get_buf(winid) == bufnr then - table.insert(buffer_windows, winid) - end - end - for _, window in ipairs(buffer_windows) do - local first = vim.fn.line('w0', window) - local last = vim.fn.line('w$', window) - local params = { - textDocument = util.make_text_document_params(bufnr), - range = { - start = { line = first - 1, character = 0 }, - ['end'] = { line = last, character = 0 }, - }, - } - vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) - end - if not only_visible then - local params = { - textDocument = util.make_text_document_params(bufnr), - range = { - start = { line = 0, character = 0 }, - ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, - }, - } - vim.lsp.buf_request(bufnr, 'textDocument/inlayHint', params) - end -end - --- |lsp-handler| for the method `textDocument/inlayHint/refresh` ---@private function M.on_refresh(err, _, ctx, _) @@ -144,8 +96,11 @@ function M.on_refresh(err, _, ctx, _) for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do for _, winid in ipairs(api.nvim_list_wins()) do if api.nvim_win_get_buf(winid) == bufnr then - refresh({ bufnr = bufnr }) - break + local bufstate = bufstates[bufnr] + if bufstate and bufstate.enabled then + util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + break + end end end end @@ -156,7 +111,9 @@ end --- Clear inlay hints ---@param bufnr (integer) Buffer handle, or 0 for current local function clear(bufnr) - bufnr = resolve_bufnr(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end if not bufstates[bufnr] then return end @@ -175,17 +132,19 @@ end local function make_request(request_bufnr) reset_timer(request_bufnr) - refresh({ bufnr = request_bufnr }) + util._refresh('textDocument/inlayHint', { bufnr = request_bufnr }) end --- Enable inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current local function enable(bufnr) - bufnr = resolve_bufnr(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end local bufstate = bufstates[bufnr] if not (bufstate and bufstate.enabled) then bufstates[bufnr] = { enabled = true, timer = nil, applied = {} } - refresh({ bufnr = bufnr }) + util._refresh('textDocument/inlayHint', { bufnr = bufnr }) api.nvim_buf_attach(bufnr, true, { on_lines = function(_, cb_bufnr) if not bufstates[cb_bufnr].enabled then @@ -201,7 +160,7 @@ local function enable(bufnr) if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then bufstates[cb_bufnr] = { enabled = true, applied = {} } end - refresh({ bufnr = cb_bufnr }) + util._refresh('textDocument/inlayHint', { bufnr = cb_bufnr }) end, on_detach = function(_, cb_bufnr) clear(cb_bufnr) @@ -222,7 +181,9 @@ end --- Disable inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current local function disable(bufnr) - bufnr = resolve_bufnr(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end if bufstates[bufnr] and bufstates[bufnr].enabled then clear(bufnr) bufstates[bufnr].enabled = nil @@ -233,7 +194,9 @@ end --- Toggle inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current local function toggle(bufnr) - bufnr = resolve_bufnr(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end local bufstate = bufstates[bufnr] if bufstate and bufstate.enabled then disable(bufnr) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 5bc0baf241..537a5eda39 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -641,6 +641,9 @@ function protocol.make_client_capabilities() }, }, textDocument = { + diagnostic = { + dynamicRegistration = false, + }, inlayHint = { dynamicRegistration = true, resolveSupport = { diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 9a6114c35b..0b06d2bbb5 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2183,6 +2183,46 @@ function M.lookup_section(settings, section) return settings end +---@private +--- Request updated LSP information for a buffer. +--- +---@param method string LSP method to call +---@param opts (nil|table) Optional arguments +--- - bufnr (integer, default: 0): Buffer to refresh +--- - only_visible (boolean, default: false): Whether to only refresh for the visible regions of the buffer +function M._refresh(method, opts) + opts = opts or {} + local bufnr = opts.bufnr + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + local only_visible = opts.only_visible or false + for _, window in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(window) == bufnr then + local first = vim.fn.line('w0', window) + local last = vim.fn.line('w$', window) + local params = { + textDocument = M.make_text_document_params(bufnr), + range = { + start = { line = first - 1, character = 0 }, + ['end'] = { line = last, character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, method, params) + end + end + if not only_visible then + local params = { + textDocument = M.make_text_document_params(bufnr), + range = { + start = { line = 0, character = 0 }, + ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, + }, + } + vim.lsp.buf_request(bufnr, method, params) + end +end + M._get_line_byte_from_position = get_line_byte_from_position ---@nodoc -- cgit From 4b57ff77febbe6073bc4c5c3a45b0ad0d5d40e6c Mon Sep 17 00:00:00 2001 From: Chris AtLee Date: Sat, 22 Jul 2023 05:00:17 -0400 Subject: refactor(lsp): use LspNotify for inlay_hint (#24411) --- runtime/lua/vim/lsp/inlay_hint.lua | 86 +++++++++++++++----------------------- 1 file changed, 34 insertions(+), 52 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 1c29e8a866..912ce6898e 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -6,28 +6,14 @@ local M = {} ---@class lsp._inlay_hint.bufstate ---@field version integer ---@field client_hint table> client_id -> (lnum -> hints) ----@field enabled boolean Whether inlay hints are enabled for the buffer ----@field timer uv.uv_timer_t? Debounce timer associated with the buffer ---@field applied table Last version of hints applied to this line - +---@field autocmd_id integer The autocmd id for the buffer ---@type table local bufstates = {} local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) ---- Reset the request debounce timer of a buffer -local function reset_timer(reset_bufnr) - local timer = bufstates[reset_bufnr].timer - if timer then - bufstates[reset_bufnr].timer = nil - if not timer:is_closing() then - timer:stop() - timer:close() - end - end -end - --- |lsp-handler| for the method `textDocument/inlayHint` --- Store hints for a specific buffer and client ---@private @@ -97,7 +83,7 @@ function M.on_refresh(err, _, ctx, _) for _, winid in ipairs(api.nvim_list_wins()) do if api.nvim_win_get_buf(winid) == bufnr then local bufstate = bufstates[bufnr] - if bufstate and bufstate.enabled then + if bufstate then util._refresh('textDocument/inlayHint', { bufnr = bufnr }) break end @@ -117,7 +103,6 @@ local function clear(bufnr) if not bufstates[bufnr] then return end - reset_timer(bufnr) local bufstate = bufstates[bufnr] local client_lens = (bufstate or {}).client_hint or {} local client_ids = vim.tbl_keys(client_lens) @@ -130,9 +115,17 @@ local function clear(bufnr) api.nvim__buf_redraw_range(bufnr, 0, -1) end -local function make_request(request_bufnr) - reset_timer(request_bufnr) - util._refresh('textDocument/inlayHint', { bufnr = request_bufnr }) +--- Disable inlay hints for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +local function disable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + clear(bufnr) + if bufstates[bufnr] and bufstates[bufnr].autocmd_id then + api.nvim_del_autocmd(bufstates[bufnr].autocmd_id) + end + bufstates[bufnr] = nil end --- Enable inlay hints for a buffer @@ -142,35 +135,37 @@ local function enable(bufnr) bufnr = api.nvim_get_current_buf() end local bufstate = bufstates[bufnr] - if not (bufstate and bufstate.enabled) then - bufstates[bufnr] = { enabled = true, timer = nil, applied = {} } - util._refresh('textDocument/inlayHint', { bufnr = bufnr }) - api.nvim_buf_attach(bufnr, true, { - on_lines = function(_, cb_bufnr) - if not bufstates[cb_bufnr].enabled then - return true + if not bufstate then + bufstates[bufnr] = { applied = {} } + bufstates[bufnr].autocmd_id = api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if opts.data.method ~= 'textDocument/didChange' then + return + end + if bufstates[bufnr] then + util._refresh('textDocument/inlayHint', { bufnr = bufnr }) end - reset_timer(cb_bufnr) - bufstates[cb_bufnr].timer = vim.defer_fn(function() - make_request(cb_bufnr) - end, 200) end, + group = augroup, + }) + util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + api.nvim_buf_attach(bufnr, true, { on_reload = function(_, cb_bufnr) clear(cb_bufnr) - if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then - bufstates[cb_bufnr] = { enabled = true, applied = {} } + if bufstates[cb_bufnr] then + bufstates[cb_bufnr].applied = {} + util._refresh('textDocument/inlayHint', { bufnr = cb_bufnr }) end - util._refresh('textDocument/inlayHint', { bufnr = cb_bufnr }) end, on_detach = function(_, cb_bufnr) - clear(cb_bufnr) - bufstates[cb_bufnr] = nil + disable(cb_bufnr) end, }) api.nvim_create_autocmd('LspDetach', { buffer = bufnr, - callback = function(opts) - clear(opts.buf) + callback = function() + disable(bufnr) end, once = true, group = augroup, @@ -178,19 +173,6 @@ local function enable(bufnr) end end ---- Disable inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current -local function disable(bufnr) - if bufnr == nil or bufnr == 0 then - bufnr = api.nvim_get_current_buf() - end - if bufstates[bufnr] and bufstates[bufnr].enabled then - clear(bufnr) - bufstates[bufnr].enabled = nil - bufstates[bufnr].timer = nil - end -end - --- Toggle inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current local function toggle(bufnr) @@ -198,7 +180,7 @@ local function toggle(bufnr) bufnr = api.nvim_get_current_buf() end local bufstate = bufstates[bufnr] - if bufstate and bufstate.enabled then + if bufstate then disable(bufnr) else enable(bufnr) -- cgit From add7e106d59b8e3822310846a850b3ed3fb5db0e Mon Sep 17 00:00:00 2001 From: Keith Smiley Date: Mon, 24 Jul 2023 08:58:59 -0700 Subject: fix(lsp): noisy warning about offset_encodings #24441 In the case you hit this warning in a buffer (like with C++ and clangd), this message potentially fires over and over again making it difficult to use the editor at all. --- runtime/lua/vim/lsp/util.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 0b06d2bbb5..4ff420cf48 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2026,7 +2026,7 @@ function M._get_offset_encoding(bufnr) if not offset_encoding then offset_encoding = this_offset_encoding elseif offset_encoding ~= this_offset_encoding then - vim.notify( + vim.notify_once( 'warning: multiple different client offset_encodings detected for buffer, this is not supported yet', vim.log.levels.WARN ) -- cgit From a37d568082ad2a6fd479bc0584f1088b51019b7f Mon Sep 17 00:00:00 2001 From: Mitchell Hanberg Date: Mon, 24 Jul 2023 12:09:53 -0400 Subject: fix(lsp): send empty "added" list when removing workspace folder #24440 When adding `workspace/didChangeWorkspaceFolders` support to my [language server](https://github.com/elixir-tools/next-ls), I noticed that when neovim removes a workspace, it sends an empty table (which is serialized to an empty JSON array) for the value in the `added` field. This does not follow the spec; the `added` table should just be empty. The following error led me to this discovery. Note the payload includes `"added" => [[]]`: ``` 22:46:48.476 [error] LSP Exited. Last message received: handle_notification %{"jsonrpc" => "2.0", "method" => "workspace/didChangeWorkspaceFolders", "params" => %{"event" => %{"added" => [[]], "removed" => [%{"name" => "/Users/mitchell/src/gen_lsp", "uri" => "file:///Users/mitchell/src/gen_lsp"}]}}} ** (MatchError) no match of right hand side value: {:error, %{"params" => %{"event" => %{"added" => [error: "expected a map"]}}}} (gen_lsp 0.4.0) lib/gen_lsp.ex:265: anonymous fn/4 in GenLSP.loop/3 (gen_lsp 0.4.0) lib/gen_lsp.ex:292: GenLSP.attempt/3 (stdlib 5.0.2) proc_lib.erl:241: :proc_lib.init_p_do_apply/3 ``` --- runtime/lua/vim/lsp/buf.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 46f582dc7e..02d8d0fa7b 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -514,7 +514,7 @@ function M.remove_workspace_folder(workspace_folder) return end local params = util.make_workspace_params( - { {} }, + {}, { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } ) for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do -- cgit From 966eb8e0b3be1b409e491d5cf1e32e82e806a134 Mon Sep 17 00:00:00 2001 From: Bruce Weirdan Date: Mon, 24 Jul 2023 19:26:17 +0200 Subject: fix(lsp): announce publishDiagnostics.dataSupport (#24442) Neovim already passed `data` element from published diagnostic to code action, but failed to announce it in client capabilities. Here is the test that shows that `data` element is returned by `vim.lsp.diagnostic.get_line_diagnostics()`: https://github.com/neovim/neovim/blob/f56c1848091bb64c63b5bc25ec74bcbd2f52bdde/test/functional/plugin/lsp/diagnostic_spec.lua#L103-L115 and then `get_line_diagnostics()` is used to construct the context for code action request: https://github.com/neovim/neovim/blob/f56c1848091bb64c63b5bc25ec74bcbd2f52bdde/runtime/lua/vim/lsp/buf.lua#L742 --- runtime/lua/vim/lsp/protocol.lua | 1 + 1 file changed, 1 insertion(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 537a5eda39..31cc071d18 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -828,6 +828,7 @@ function protocol.make_client_capabilities() return res end)(), }, + dataSupport = true, }, callHierarchy = { dynamicRegistration = false, -- cgit From 7668f89d5be6d463bf6ab0c2d3a0393e3ec26e7f Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 24 Jul 2023 20:21:35 +0200 Subject: fix(lsp): replace @private with @nodoc for public client functions (#24415) * fix(lsp): replace @private with @nodoc for public client functions To prevent lua-ls warnings in plugins which use the functions. * fix(lsp): remove duplicate type annotations/class definitions These annotations became duplicate with https://github.com/neovim/neovim/pull/23750 --- runtime/lua/vim/lsp/types.lua | 79 ++----------------------------------------- 1 file changed, 2 insertions(+), 77 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua index cdfbcfb11b..98e948c945 100644 --- a/runtime/lua/vim/lsp/types.lua +++ b/runtime/lua/vim/lsp/types.lua @@ -5,92 +5,17 @@ ---@class lsp.HandlerContext ---@field method string ---@field client_id integer ----@field bufnr integer ----@field params any +---@field bufnr? integer +---@field params? any ---@class lsp.ResponseError ---@field code integer ---@field message string ---@field data string|number|boolean|table[]|table|nil ----@class lsp.ShowMessageRequestParams ----@field type lsp.MessageType ----@field message string ----@field actions nil|lsp.MessageActionItem[] - ----@class lsp.MessageActionItem ----@field title string - ----@class lsp.FileEvent ----@field uri string ----@field type lsp.FileChangeType - ----@class lsp.Position ----@field line integer ----@field character integer - ----@class lsp.Range ----@field start lsp.Position ----@field end lsp.Position - ----@class lsp.Diagnostic ----@field range lsp.Range ----@field message string ----@field severity? lsp.DiagnosticSeverity ----@field code integer | string ----@field source string ----@field tags? lsp.DiagnosticTag[] ----@field relatedInformation DiagnosticRelatedInformation[] - --- @class lsp.DocumentFilter --- @field language? string --- @field scheme? string --- @field pattern? string ---- @alias lsp.DocumentSelector lsp.DocumentFilter[] - --- @alias lsp.RegisterOptions any | lsp.StaticRegistrationOptions | lsp.TextDocumentRegistrationOptions - ---- @class lsp.Registration ---- @field id string ---- @field method string ---- @field registerOptions? lsp.RegisterOptions - ---- @alias lsp.RegistrationParams {registrations: lsp.Registration[]} - ---- @class lsp.StaticRegistrationOptions ---- @field id? string - ---- @class lsp.TextDocumentRegistrationOptions ---- @field documentSelector? lsp.DocumentSelector - ---- @class lsp.Unregistration ---- @field id string ---- @field method string - ---- @alias lsp.UnregistrationParams {unregisterations: lsp.Unregistration[]} - ----@class lsp.Location ----@field uri string ----@field range lsp.Range - ----@class lsp.MarkupContent ----@field kind string ----@field value string - ----@class lsp.InlayHintLabelPart ----@field value string ----@field tooltip? string | lsp.MarkupContent ----@field location? lsp.Location - ----@class lsp.TextEdit ----@field range lsp.Range ----@field newText string - ----@class lsp.InlayHint ----@field position lsp.Position ----@field label string | lsp.InlayHintLabelPart[] ----@field kind? integer ----@field textEdits? lsp.TextEdit[] ----@field paddingLeft? boolean ----@field paddingRight? boolean -- cgit From 4d0f4c3de9cbdcf85e606b5aaf9488820b95b679 Mon Sep 17 00:00:00 2001 From: Raphael Date: Tue, 25 Jul 2023 19:38:48 +0800 Subject: fix(lsp): E403 if doc contains multiple codeblocks #24458 Problem: Content that has codeblocks with different languages, results in multiple calls to: syntax include vim syntax/vim.vim which raises error: E403: syntax sync: line continuations pattern specified twice Before ba8f19ebb67ca27d746f4b1cd902ab3d807eace3, this was avoided by using pcall() to ignore the error. Solution: Restore the use of pcall() to ignore the error. We plan to replace this logic with a treesitter approach, so this is good enough for now. Fix #24431 --- runtime/lua/vim/lsp/util.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 4ff420cf48..4d3071fd68 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1466,7 +1466,7 @@ function M.stylize_markdown(bufnr, contents, opts) if #api.nvim_get_runtime_file(('syntax/%s.vim'):format(ft), true) == 0 then return end - vim.cmd(string.format('syntax include %s syntax/%s.vim', lang, ft)) + pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) langs[lang] = true end vim.cmd( -- cgit From 20c331915f4e317c615c7cfea469a9baedd2e4f7 Mon Sep 17 00:00:00 2001 From: Christoph Hasse Date: Tue, 25 Jul 2023 08:40:13 -0400 Subject: fix(lsp): SignatureHelp docstring is not escaped #16702 Problem: Nvim LSP client always treats signature.documentation as markdown, even if the server returns a plain string. Per https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#signatureInformation in a SignatureInformation response, the documentation field can be either "string" or "MarkupContent". Solution: If signature.documentation is a string, treat it as "plaintext". Closes #16563 --- runtime/lua/vim/lsp/util.lua | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 4d3071fd68..738e23ff28 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1002,6 +1002,12 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers end list_extend(contents, split(label, '\n', { plain = true })) if signature.documentation then + -- if LSP returns plain string, we treat it as plaintext. This avoids + -- special characters like underscore or similar from being interpreted + -- as markdown font modifiers + if type(signature.documentation) == 'string' then + signature.documentation = { kind = 'plaintext', value = signature.documentation } + end M.convert_input_to_markdown_lines(signature.documentation, contents) end if signature.parameters and #signature.parameters > 0 then -- cgit From 74bd4aba57d2f1b224abe46a6de82911d14ef6c1 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Tue, 25 Jul 2023 16:57:19 +0200 Subject: fix(lsp): fix multi client handling workspace_folder methods (#18839) `buf_notify` sends the notification to all clients of a buffer, calling that inside a loop over clients multiplies the amount of notifications. --- runtime/lua/vim/lsp/buf.lua | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 02d8d0fa7b..5e0e429021 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -480,11 +480,13 @@ function M.add_workspace_folder(workspace_folder) print(workspace_folder, ' is not a valid directory') return end - local params = util.make_workspace_params( - { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } }, - {} - ) - for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do + local new_workspace = { + uri = vim.uri_from_fname(workspace_folder), + name = workspace_folder, + } + local params = { event = { added = { new_workspace }, removed = {} } } + local bufnr = vim.api.nvim_get_current_buf() + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do local found = false for _, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then @@ -494,11 +496,11 @@ function M.add_workspace_folder(workspace_folder) end end if not found then - vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) + client.notify('workspace/didChangeWorkspaceFolders', params) if not client.workspace_folders then client.workspace_folders = {} end - table.insert(client.workspace_folders, params.event.added[1]) + table.insert(client.workspace_folders, new_workspace) end end end @@ -513,14 +515,16 @@ function M.remove_workspace_folder(workspace_folder) if not (workspace_folder and #workspace_folder > 0) then return end - local params = util.make_workspace_params( - {}, - { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } - ) - for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do - for idx, folder in pairs(client.workspace_folders or {}) do + local workspace = { + uri = vim.uri_from_fname(workspace_folder), + name = workspace_folder, + } + local params = { event = { added = {}, removed = { workspace } } } + local bufnr = vim.api.nvim_get_current_buf() + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do + for idx, folder in pairs(client.workspace_folders) do if folder.name == workspace_folder then - vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) + client.notify('workspace/didChangeWorkspaceFolders', params) client.workspace_folders[idx] = nil return end -- cgit From e55e80d51ca5d85770981bffb9254badc3662e0c Mon Sep 17 00:00:00 2001 From: Chris AtLee Date: Tue, 1 Aug 2023 08:13:52 -0400 Subject: fix(lsp): inlay hints: "Failed to delete autocmd" when closing buffer #24469 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: "Failed to delete autocmd" error when deleting LspNotify autocmd. #24456 Solution: Change a few things in the inlay_hint and diagnostic LSP code: 1. Re-introduce the `enabled` flag for the buffer state tables. Previously I was relying on the presence of an autocmd id in the state table to track whether inlay_hint / diagnostic was enabled for a buffer. There are two reasons why this doesn't work well: - Each time inlay_hint / diagnostic is enabled, we call `nvim_buf_attach` on the buffer, resulting in multiple `on_reload` or `on_detach` callbacks being registered. - Commands like `bwipeout` delete buffer local autocmds, sometimes before our `on_detach` callbacks have a chance to delete them first. This causes the - Use module local enabled state for diagnostic as well. bwipeout can race with on_detach callbacks for deleting autocmds. Error referenced in #24456. 2. Change the `LspDetach` autocmd to run each time (i.e., remove the `once` flag). Since we're only registering autocmds once per buffer now, we need to make sure that we set the enabled flag properly each time the LSP client detaches from the buffer. - Remove `once` from the LspDetach autocmds for inlay_hint and diagnostic. We only set up the autocmd once now. Gets removed when buffer is deleted. 3. Have the `LspNotify` handler also refresh the inlay_hint / diagnostics when receiving the `textDocument/didOpen` event. Before this point, the LSP backend doesn't have the contents of the buffer, so can't provide inlay hints or diagnostics. Downsides of this approach: * When inlay_hint / diagnostics are disabled on a buffer, it will continue to receive `LspNotify` events for that buffer. The callback exits early since the `enabled` flag is false. Alternatives: * Can we wrap the call to `nvim_del_autocmd` in `pcall` to swallow any errors resulting from trying to delete the autocmd? Fixes #24456 Helped-by: Maria José Solano --- runtime/lua/vim/lsp/diagnostic.lua | 85 +++++++++++++++++++++----------------- runtime/lua/vim/lsp/inlay_hint.lua | 35 +++++++++------- 2 files changed, 67 insertions(+), 53 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 34be13096d..44bb90d985 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -392,19 +392,18 @@ local function clear(bufnr) end end ---- autocmd ids for LspNotify handlers per buffer ---- @private ---- @type table -local _autocmd_ids = {} +---@class lsp.diagnostic.bufstate +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table +local bufstates = {} --- Disable pull diagnostics for a buffer --- @private local function disable(bufnr) - if not _autocmd_ids[bufnr] then - return + local bufstate = bufstates[bufnr] + if bufstate then + bufstate.enabled = false end - api.nvim_del_autocmd(_autocmd_ids[bufnr]) - _autocmd_ids[bufnr] = nil clear(bufnr) end @@ -416,38 +415,46 @@ function M._enable(bufnr) bufnr = api.nvim_get_current_buf() end - if _autocmd_ids[bufnr] then - return + if not bufstates[bufnr] then + bufstates[bufnr] = { enabled = true } + + api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if + opts.data.method ~= 'textDocument/didChange' + and opts.data.method ~= 'textDocument/didOpen' + then + return + end + if bufstates[bufnr] and bufstates[bufnr].enabled then + util._refresh('textDocument/diagnostic', { bufnr = bufnr, only_visible = true }) + end + end, + group = augroup, + }) + + api.nvim_buf_attach(bufnr, false, { + on_reload = function() + if bufstates[bufnr] and bufstates[bufnr].enabled then + util._refresh('textDocument/diagnostic', { bufnr = bufnr }) + end + end, + on_detach = function() + disable(bufnr) + end, + }) + + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function() + disable(bufnr) + end, + group = augroup, + }) + else + bufstates[bufnr].enabled = true end - - _autocmd_ids[bufnr] = api.nvim_create_autocmd('LspNotify', { - buffer = bufnr, - callback = function(opts) - if opts.data.method ~= 'textDocument/didChange' then - return - end - util._refresh('textDocument/diagnostic', { bufnr = bufnr, only_visible = true }) - end, - group = augroup, - }) - - api.nvim_buf_attach(bufnr, false, { - on_reload = function() - util._refresh('textDocument/diagnostic', { bufnr = bufnr }) - end, - on_detach = function() - disable(bufnr) - end, - }) - - api.nvim_create_autocmd('LspDetach', { - buffer = bufnr, - callback = function() - disable(bufnr) - end, - once = true, - group = augroup, - }) end return M diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 912ce6898e..2bf0fb9cb2 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -3,12 +3,12 @@ local log = require('vim.lsp.log') local api = vim.api local M = {} ----@class lsp._inlay_hint.bufstate +---@class lsp.inlay_hint.bufstate ---@field version integer ---@field client_hint table> client_id -> (lnum -> hints) ---@field applied table Last version of hints applied to this line ----@field autocmd_id integer The autocmd id for the buffer ----@type table +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table local bufstates = {} local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') @@ -31,6 +31,9 @@ function M.on_inlayhint(err, result, ctx, _) return end local bufstate = bufstates[bufnr] + if not bufstate or not bufstate.enabled then + return + end if not (bufstate.client_hint and bufstate.version) then bufstate.client_hint = vim.defaulttable() bufstate.version = ctx.version @@ -122,10 +125,9 @@ local function disable(bufnr) bufnr = api.nvim_get_current_buf() end clear(bufnr) - if bufstates[bufnr] and bufstates[bufnr].autocmd_id then - api.nvim_del_autocmd(bufstates[bufnr].autocmd_id) + if bufstates[bufnr] then + bufstates[bufnr] = { enabled = false, applied = {} } end - bufstates[bufnr] = nil end --- Enable inlay hints for a buffer @@ -136,24 +138,27 @@ local function enable(bufnr) end local bufstate = bufstates[bufnr] if not bufstate then - bufstates[bufnr] = { applied = {} } - bufstates[bufnr].autocmd_id = api.nvim_create_autocmd('LspNotify', { + bufstates[bufnr] = { applied = {}, enabled = true } + api.nvim_create_autocmd('LspNotify', { buffer = bufnr, callback = function(opts) - if opts.data.method ~= 'textDocument/didChange' then + if + opts.data.method ~= 'textDocument/didChange' + and opts.data.method ~= 'textDocument/didOpen' + then return end - if bufstates[bufnr] then + if bufstates[bufnr] and bufstates[bufnr].enabled then util._refresh('textDocument/inlayHint', { bufnr = bufnr }) end end, group = augroup, }) util._refresh('textDocument/inlayHint', { bufnr = bufnr }) - api.nvim_buf_attach(bufnr, true, { + api.nvim_buf_attach(bufnr, false, { on_reload = function(_, cb_bufnr) clear(cb_bufnr) - if bufstates[cb_bufnr] then + if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then bufstates[cb_bufnr].applied = {} util._refresh('textDocument/inlayHint', { bufnr = cb_bufnr }) end @@ -167,9 +172,11 @@ local function enable(bufnr) callback = function() disable(bufnr) end, - once = true, group = augroup, }) + else + bufstate.enabled = true + util._refresh('textDocument/inlayHint', { bufnr = bufnr }) end end @@ -180,7 +187,7 @@ local function toggle(bufnr) bufnr = api.nvim_get_current_buf() end local bufstate = bufstates[bufnr] - if bufstate then + if bufstate and bufstate.enabled then disable(bufnr) else enable(bufnr) -- cgit From da09f9b551badfb3fd363589009168560ae607f6 Mon Sep 17 00:00:00 2001 From: mathew Date: Fri, 28 Jul 2023 15:24:18 +0800 Subject: feat(gen_lsp.lua): protocol.Methods #24504 --- runtime/lua/vim/lsp/protocol.lua | 270 +++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/types/protocol.lua | 2 +- 2 files changed, 271 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 31cc071d18..e45baa59c5 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -923,4 +923,274 @@ function protocol.resolve_capabilities(server_capabilities) return server_capabilities end +-- Generated by lsp_types.lua, keep at end of file. +--- LSP method names. +--- +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#metaModel +protocol.Methods = { + --- The initialize request is sent from the client to the server. + --- It is sent once as the request after starting up the server. + --- The requests parameter is of type {@link InitializeParams} + --- the response if of type {@link InitializeResult} of a Thenable that + --- resolves to such. + initialize = 'initialize', + --- A shutdown request is sent from the client to the server. + --- It is sent once when the client decides to shutdown the + --- server. The only notification that is sent after a shutdown request + --- is the exit event. + shutdown = 'shutdown', + --- The `client/registerCapability` request is sent from the server to the client to register a new capability + --- handler on the client side. + client_registerCapability = 'client/registerCapability', + --- The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability + --- handler on the client side. + client_unregisterCapability = 'client/unregisterCapability', + --- A request to resolve the implementation locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_implementation = 'textDocument/implementation', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_typeDefinition = 'textDocument/typeDefinition', + --- A request to list all color symbols found in a given text document. The request's + --- parameter is of type {@link DocumentColorParams} the + --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable + --- that resolves to such. + textDocument_documentColor = 'textDocument/documentColor', + --- A request to list all presentation for a color. The request's + --- parameter is of type {@link ColorPresentationParams} the + --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable + --- that resolves to such. + textDocument_colorPresentation = 'textDocument/colorPresentation', + --- A request to provide folding ranges in a document. The request's + --- parameter is of type {@link FoldingRangeParams}, the + --- response is of type {@link FoldingRangeList} or a Thenable + --- that resolves to such. + textDocument_foldingRange = 'textDocument/foldingRange', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Declaration} + --- or a typed array of {@link DeclarationLink} or a Thenable that resolves + --- to such. + textDocument_declaration = 'textDocument/declaration', + --- A request to provide selection ranges in a document. The request's + --- parameter is of type {@link SelectionRangeParams}, the + --- response is of type {@link SelectionRange SelectionRange[]} or a Thenable + --- that resolves to such. + textDocument_selectionRange = 'textDocument/selectionRange', + --- A request to result a `CallHierarchyItem` in a document at a given position. + --- Can be used as an input to an incoming or outgoing call hierarchy. + --- @since 3.16.0 + textDocument_prepareCallHierarchy = 'textDocument/prepareCallHierarchy', + --- @since 3.16.0 + textDocument_semanticTokens_full = 'textDocument/semanticTokens/full', + --- @since 3.16.0 + textDocument_semanticTokens_full_delta = 'textDocument/semanticTokens/full/delta', + --- @since 3.16.0 + textDocument_semanticTokens_range = 'textDocument/semanticTokens/range', + --- A request to provide ranges that can be edited together. + --- @since 3.16.0 + textDocument_linkedEditingRange = 'textDocument/linkedEditingRange', + --- A request to get the moniker of a symbol at a given text document position. + --- The request parameter is of type {@link TextDocumentPositionParams}. + --- The response is of type {@link Moniker Moniker[]} or `null`. + textDocument_moniker = 'textDocument/moniker', + --- A request to result a `TypeHierarchyItem` in a document at a given position. + --- Can be used as an input to a subtypes or supertypes type hierarchy. + --- @since 3.17.0 + textDocument_prepareTypeHierarchy = 'textDocument/prepareTypeHierarchy', + --- A request to provide inline values in a document. The request's parameter is of + --- type {@link InlineValueParams}, the response is of type + --- {@link InlineValue InlineValue[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlineValue = 'textDocument/inlineValue', + --- A request to provide inlay hints in a document. The request's parameter is of + --- type {@link InlayHintsParams}, the response is of type + --- {@link InlayHint InlayHint[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlayHint = 'textDocument/inlayHint', + --- The document diagnostic request definition. + --- @since 3.17.0 + textDocument_diagnostic = 'textDocument/diagnostic', + --- A request to provide inline completions in a document. The request's parameter is of + --- type {@link InlineCompletionParams}, the response is of type + --- {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. + --- @since 3.18.0 + textDocument_inlineCompletion = 'textDocument/inlineCompletion', + --- A document will save request is sent from the client to the server before + --- the document is actually saved. The request can return an array of TextEdits + --- which will be applied to the text document before it is saved. Please note that + --- clients might drop results if computing the text edits took too long or if a + --- server constantly fails on this request. This is done to keep the save fast and + --- reliable. + textDocument_willSaveWaitUntil = 'textDocument/willSaveWaitUntil', + --- Request to request completion at a given text document position. The request's + --- parameter is of type {@link TextDocumentPosition} the response + --- is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList} + --- or a Thenable that resolves to such. + --- The request can delay the computation of the {@link CompletionItem.detail `detail`} + --- and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve` + --- request. However, properties that are needed for the initial sorting and filtering, like `sortText`, + --- `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. + textDocument_completion = 'textDocument/completion', + --- Request to request hover information at a given text document position. The request's + --- parameter is of type {@link TextDocumentPosition} the response is of + --- type {@link Hover} or a Thenable that resolves to such. + textDocument_hover = 'textDocument/hover', + textDocument_signatureHelp = 'textDocument/signatureHelp', + --- A request to resolve the definition location of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPosition] + --- (#TextDocumentPosition) the response is of either type {@link Definition} + --- or a typed array of {@link DefinitionLink} or a Thenable that resolves + --- to such. + textDocument_definition = 'textDocument/definition', + --- A request to resolve project-wide references for the symbol denoted + --- by the given text document position. The request's parameter is of + --- type {@link ReferenceParams} the response is of type + --- {@link Location Location[]} or a Thenable that resolves to such. + textDocument_references = 'textDocument/references', + --- Request to resolve a {@link DocumentHighlight} for a given + --- text document position. The request's parameter is of type [TextDocumentPosition] + --- (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] + --- (#DocumentHighlight) or a Thenable that resolves to such. + textDocument_documentHighlight = 'textDocument/documentHighlight', + --- A request to list all symbols found in a given text document. The request's + --- parameter is of type {@link TextDocumentIdentifier} the + --- response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable + --- that resolves to such. + textDocument_documentSymbol = 'textDocument/documentSymbol', + --- A request to provide commands for the given text document and range. + textDocument_codeAction = 'textDocument/codeAction', + --- A request to provide code lens for the given text document. + textDocument_codeLens = 'textDocument/codeLens', + --- A request to provide document links + textDocument_documentLink = 'textDocument/documentLink', + --- A request to to format a whole document. + textDocument_formatting = 'textDocument/formatting', + --- A request to format a range in a document. + textDocument_rangeFormatting = 'textDocument/rangeFormatting', + --- A request to format ranges in a document. + --- @since 3.18.0 + --- @proposed + textDocument_rangesFormatting = 'textDocument/rangesFormatting', + --- A request to format a document on type. + textDocument_onTypeFormatting = 'textDocument/onTypeFormatting', + --- A request to rename a symbol. + textDocument_rename = 'textDocument/rename', + --- A request to test and perform the setup necessary for a rename. + --- @since 3.16 - support for default behavior + textDocument_prepareRename = 'textDocument/prepareRename', + --- The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. + workspace_workspaceFolders = 'workspace/workspaceFolders', + --- The 'workspace/configuration' request is sent from the server to the client to fetch a certain + --- configuration setting. + --- This pull model replaces the old push model were the client signaled configuration change via an + --- event. If the server still needs to react to configuration changes (since the server caches the + --- result of `workspace/configuration` requests) the server should register for an empty configuration + --- change event and empty the cache if such an event is received. + workspace_configuration = 'workspace/configuration', + --- @since 3.16.0 + workspace_semanticTokens_refresh = 'workspace/semanticTokens/refresh', + --- The will create files request is sent from the client to the server before files are actually + --- created as long as the creation is triggered from within the client. + --- The request can return a `WorkspaceEdit` which will be applied to workspace before the + --- files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file + --- to be created. + --- @since 3.16.0 + workspace_willCreateFiles = 'workspace/willCreateFiles', + --- The will rename files request is sent from the client to the server before files are actually + --- renamed as long as the rename is triggered from within the client. + --- @since 3.16.0 + workspace_willRenameFiles = 'workspace/willRenameFiles', + --- The did delete files notification is sent from the client to the server when + --- files were deleted from within the client. + --- @since 3.16.0 + workspace_willDeleteFiles = 'workspace/willDeleteFiles', + --- @since 3.17.0 + workspace_inlineValue_refresh = 'workspace/inlineValue/refresh', + --- @since 3.17.0 + workspace_inlayHint_refresh = 'workspace/inlayHint/refresh', + --- The workspace diagnostic request definition. + --- @since 3.17.0 + workspace_diagnostic = 'workspace/diagnostic', + --- The diagnostic refresh request definition. + --- @since 3.17.0 + workspace_diagnostic_refresh = 'workspace/diagnostic/refresh', + --- A request to list project-wide symbols matching the query string given + --- by the {@link WorkspaceSymbolParams}. The response is + --- of type {@link SymbolInformation SymbolInformation[]} or a Thenable that + --- resolves to such. + --- @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients + --- need to advertise support for WorkspaceSymbols via the client capability + --- `workspace.symbol.resolveSupport`. + workspace_symbol = 'workspace/symbol', + --- A request to refresh all code actions + --- @since 3.16.0 + workspace_codeLens_refresh = 'workspace/codeLens/refresh', + --- A request send from the client to the server to execute a command. The request might return + --- a workspace edit which the client will apply to the workspace. + workspace_executeCommand = 'workspace/executeCommand', + --- A request sent from the server to the client to modified certain resources. + workspace_applyEdit = 'workspace/applyEdit', + --- The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress + --- reporting from the server. + window_workDoneProgress_create = 'window/workDoneProgress/create', + --- A request to resolve the incoming calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_incomingCalls = 'callHierarchy/incomingCalls', + --- A request to resolve the outgoing calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_outgoingCalls = 'callHierarchy/outgoingCalls', + --- A request to show a document. This request might open an + --- external program depending on the value of the URI to open. + --- For example a request to open `https://code.visualstudio.com/` + --- will very likely open the URI in a WEB browser. + --- @since 3.16.0 + window_showDocument = 'window/showDocument', + --- A request to resolve the supertypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_supertypes = 'typeHierarchy/supertypes', + --- A request to resolve the subtypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_subtypes = 'typeHierarchy/subtypes', + --- A request to resolve additional properties for an inlay hint. + --- The request's parameter is of type {@link InlayHint}, the response is + --- of type {@link InlayHint} or a Thenable that resolves to such. + --- @since 3.17.0 + inlayHint_resolve = 'inlayHint/resolve', + --- The show message request is sent from the server to the client to show a message + --- and a set of options actions to the user. + window_showMessageRequest = 'window/showMessageRequest', + --- Request to resolve additional information for a given completion item.The request's + --- parameter is of type {@link CompletionItem} the response + --- is of type {@link CompletionItem} or a Thenable that resolves to such. + completionItem_resolve = 'completionItem/resolve', + --- Request to resolve additional information for a given code action.The request's + --- parameter is of type {@link CodeAction} the response + --- is of type {@link CodeAction} or a Thenable that resolves to such. + codeAction_resolve = 'codeAction/resolve', + --- A request to resolve the range inside the workspace + --- symbol's location. + --- @since 3.17.0 + workspaceSymbol_resolve = 'workspaceSymbol/resolve', + --- A request to resolve a command for a given code lens. + codeLens_resolve = 'codeLens/resolve', + --- Request to resolve additional information for a given document link. The request's + --- parameter is of type {@link DocumentLink} the response + --- is of type {@link DocumentLink} or a Thenable that resolves to such. + documentLink_resolve = 'documentLink/resolve', +} +local function freeze(t) + return setmetatable({}, { + __index = t, + __newindex = function() + error('cannot modify immutable table') + end, + }) +end +protocol.Methods = freeze(protocol.Methods) + return protocol diff --git a/runtime/lua/vim/lsp/types/protocol.lua b/runtime/lua/vim/lsp/types/protocol.lua index 4b6660eb51..241d64e6e5 100644 --- a/runtime/lua/vim/lsp/types/protocol.lua +++ b/runtime/lua/vim/lsp/types/protocol.lua @@ -1,7 +1,7 @@ --[[ This file is autogenerated from scripts/lsp_types.lua Regenerate: -nvim -l scripts/lsp_types.lua gen --runtime/lua/vim/lsp/types/protocol.lua +nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/protocol.lua --]] ---@alias lsp.null nil -- cgit From f41496ce74fb30c18bb9a03027a172800b269643 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Tue, 1 Aug 2023 15:52:53 +0200 Subject: feat(gen_lsp.lua): sort by name, handle failure #24504 --- runtime/lua/vim/lsp/protocol.lua | 362 ++++++++++++++++----------------- runtime/lua/vim/lsp/types/protocol.lua | 73 ++++--- 2 files changed, 215 insertions(+), 220 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index e45baa59c5..3844c697c6 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -923,110 +923,62 @@ function protocol.resolve_capabilities(server_capabilities) return server_capabilities end --- Generated by lsp_types.lua, keep at end of file. +-- Generated by gen_lsp.lua, keep at end of file. --- LSP method names. --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#metaModel protocol.Methods = { + --- A request to resolve the incoming calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_incomingCalls = 'callHierarchy/incomingCalls', + --- A request to resolve the outgoing calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_outgoingCalls = 'callHierarchy/outgoingCalls', + --- The `client/registerCapability` request is sent from the server to the client to register a new capability + --- handler on the client side. + client_registerCapability = 'client/registerCapability', + --- The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability + --- handler on the client side. + client_unregisterCapability = 'client/unregisterCapability', + --- Request to resolve additional information for a given code action.The request's + --- parameter is of type {@link CodeAction} the response + --- is of type {@link CodeAction} or a Thenable that resolves to such. + codeAction_resolve = 'codeAction/resolve', + --- A request to resolve a command for a given code lens. + codeLens_resolve = 'codeLens/resolve', + --- Request to resolve additional information for a given completion item.The request's + --- parameter is of type {@link CompletionItem} the response + --- is of type {@link CompletionItem} or a Thenable that resolves to such. + completionItem_resolve = 'completionItem/resolve', + --- Request to resolve additional information for a given document link. The request's + --- parameter is of type {@link DocumentLink} the response + --- is of type {@link DocumentLink} or a Thenable that resolves to such. + documentLink_resolve = 'documentLink/resolve', --- The initialize request is sent from the client to the server. --- It is sent once as the request after starting up the server. --- The requests parameter is of type {@link InitializeParams} --- the response if of type {@link InitializeResult} of a Thenable that --- resolves to such. initialize = 'initialize', + --- A request to resolve additional properties for an inlay hint. + --- The request's parameter is of type {@link InlayHint}, the response is + --- of type {@link InlayHint} or a Thenable that resolves to such. + --- @since 3.17.0 + inlayHint_resolve = 'inlayHint/resolve', --- A shutdown request is sent from the client to the server. --- It is sent once when the client decides to shutdown the --- server. The only notification that is sent after a shutdown request --- is the exit event. shutdown = 'shutdown', - --- The `client/registerCapability` request is sent from the server to the client to register a new capability - --- handler on the client side. - client_registerCapability = 'client/registerCapability', - --- The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability - --- handler on the client side. - client_unregisterCapability = 'client/unregisterCapability', - --- A request to resolve the implementation locations of a symbol at a given text - --- document position. The request's parameter is of type [TextDocumentPositionParams] - --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a - --- Thenable that resolves to such. - textDocument_implementation = 'textDocument/implementation', - --- A request to resolve the type definition locations of a symbol at a given text - --- document position. The request's parameter is of type [TextDocumentPositionParams] - --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a - --- Thenable that resolves to such. - textDocument_typeDefinition = 'textDocument/typeDefinition', - --- A request to list all color symbols found in a given text document. The request's - --- parameter is of type {@link DocumentColorParams} the - --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable - --- that resolves to such. - textDocument_documentColor = 'textDocument/documentColor', + --- A request to provide commands for the given text document and range. + textDocument_codeAction = 'textDocument/codeAction', + --- A request to provide code lens for the given text document. + textDocument_codeLens = 'textDocument/codeLens', --- A request to list all presentation for a color. The request's --- parameter is of type {@link ColorPresentationParams} the --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable --- that resolves to such. textDocument_colorPresentation = 'textDocument/colorPresentation', - --- A request to provide folding ranges in a document. The request's - --- parameter is of type {@link FoldingRangeParams}, the - --- response is of type {@link FoldingRangeList} or a Thenable - --- that resolves to such. - textDocument_foldingRange = 'textDocument/foldingRange', - --- A request to resolve the type definition locations of a symbol at a given text - --- document position. The request's parameter is of type [TextDocumentPositionParams] - --- (#TextDocumentPositionParams) the response is of type {@link Declaration} - --- or a typed array of {@link DeclarationLink} or a Thenable that resolves - --- to such. - textDocument_declaration = 'textDocument/declaration', - --- A request to provide selection ranges in a document. The request's - --- parameter is of type {@link SelectionRangeParams}, the - --- response is of type {@link SelectionRange SelectionRange[]} or a Thenable - --- that resolves to such. - textDocument_selectionRange = 'textDocument/selectionRange', - --- A request to result a `CallHierarchyItem` in a document at a given position. - --- Can be used as an input to an incoming or outgoing call hierarchy. - --- @since 3.16.0 - textDocument_prepareCallHierarchy = 'textDocument/prepareCallHierarchy', - --- @since 3.16.0 - textDocument_semanticTokens_full = 'textDocument/semanticTokens/full', - --- @since 3.16.0 - textDocument_semanticTokens_full_delta = 'textDocument/semanticTokens/full/delta', - --- @since 3.16.0 - textDocument_semanticTokens_range = 'textDocument/semanticTokens/range', - --- A request to provide ranges that can be edited together. - --- @since 3.16.0 - textDocument_linkedEditingRange = 'textDocument/linkedEditingRange', - --- A request to get the moniker of a symbol at a given text document position. - --- The request parameter is of type {@link TextDocumentPositionParams}. - --- The response is of type {@link Moniker Moniker[]} or `null`. - textDocument_moniker = 'textDocument/moniker', - --- A request to result a `TypeHierarchyItem` in a document at a given position. - --- Can be used as an input to a subtypes or supertypes type hierarchy. - --- @since 3.17.0 - textDocument_prepareTypeHierarchy = 'textDocument/prepareTypeHierarchy', - --- A request to provide inline values in a document. The request's parameter is of - --- type {@link InlineValueParams}, the response is of type - --- {@link InlineValue InlineValue[]} or a Thenable that resolves to such. - --- @since 3.17.0 - textDocument_inlineValue = 'textDocument/inlineValue', - --- A request to provide inlay hints in a document. The request's parameter is of - --- type {@link InlayHintsParams}, the response is of type - --- {@link InlayHint InlayHint[]} or a Thenable that resolves to such. - --- @since 3.17.0 - textDocument_inlayHint = 'textDocument/inlayHint', - --- The document diagnostic request definition. - --- @since 3.17.0 - textDocument_diagnostic = 'textDocument/diagnostic', - --- A request to provide inline completions in a document. The request's parameter is of - --- type {@link InlineCompletionParams}, the response is of type - --- {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. - --- @since 3.18.0 - textDocument_inlineCompletion = 'textDocument/inlineCompletion', - --- A document will save request is sent from the client to the server before - --- the document is actually saved. The request can return an array of TextEdits - --- which will be applied to the text document before it is saved. Please note that - --- clients might drop results if computing the text edits took too long or if a - --- server constantly fails on this request. This is done to keep the save fast and - --- reliable. - textDocument_willSaveWaitUntil = 'textDocument/willSaveWaitUntil', --- Request to request completion at a given text document position. The request's --- parameter is of type {@link TextDocumentPosition} the response --- is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList} @@ -1036,55 +988,153 @@ protocol.Methods = { --- request. However, properties that are needed for the initial sorting and filtering, like `sortText`, --- `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. textDocument_completion = 'textDocument/completion', - --- Request to request hover information at a given text document position. The request's - --- parameter is of type {@link TextDocumentPosition} the response is of - --- type {@link Hover} or a Thenable that resolves to such. - textDocument_hover = 'textDocument/hover', - textDocument_signatureHelp = 'textDocument/signatureHelp', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Declaration} + --- or a typed array of {@link DeclarationLink} or a Thenable that resolves + --- to such. + textDocument_declaration = 'textDocument/declaration', --- A request to resolve the definition location of a symbol at a given text --- document position. The request's parameter is of type [TextDocumentPosition] --- (#TextDocumentPosition) the response is of either type {@link Definition} --- or a typed array of {@link DefinitionLink} or a Thenable that resolves --- to such. textDocument_definition = 'textDocument/definition', - --- A request to resolve project-wide references for the symbol denoted - --- by the given text document position. The request's parameter is of - --- type {@link ReferenceParams} the response is of type - --- {@link Location Location[]} or a Thenable that resolves to such. - textDocument_references = 'textDocument/references', + --- The document diagnostic request definition. + --- @since 3.17.0 + textDocument_diagnostic = 'textDocument/diagnostic', + --- A request to list all color symbols found in a given text document. The request's + --- parameter is of type {@link DocumentColorParams} the + --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable + --- that resolves to such. + textDocument_documentColor = 'textDocument/documentColor', --- Request to resolve a {@link DocumentHighlight} for a given --- text document position. The request's parameter is of type [TextDocumentPosition] --- (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] --- (#DocumentHighlight) or a Thenable that resolves to such. textDocument_documentHighlight = 'textDocument/documentHighlight', + --- A request to provide document links + textDocument_documentLink = 'textDocument/documentLink', --- A request to list all symbols found in a given text document. The request's --- parameter is of type {@link TextDocumentIdentifier} the --- response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable --- that resolves to such. textDocument_documentSymbol = 'textDocument/documentSymbol', - --- A request to provide commands for the given text document and range. - textDocument_codeAction = 'textDocument/codeAction', - --- A request to provide code lens for the given text document. - textDocument_codeLens = 'textDocument/codeLens', - --- A request to provide document links - textDocument_documentLink = 'textDocument/documentLink', - --- A request to to format a whole document. + --- A request to provide folding ranges in a document. The request's + --- parameter is of type {@link FoldingRangeParams}, the + --- response is of type {@link FoldingRangeList} or a Thenable + --- that resolves to such. + textDocument_foldingRange = 'textDocument/foldingRange', + --- A request to format a whole document. textDocument_formatting = 'textDocument/formatting', + --- Request to request hover information at a given text document position. The request's + --- parameter is of type {@link TextDocumentPosition} the response is of + --- type {@link Hover} or a Thenable that resolves to such. + textDocument_hover = 'textDocument/hover', + --- A request to resolve the implementation locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_implementation = 'textDocument/implementation', + --- A request to provide inlay hints in a document. The request's parameter is of + --- type {@link InlayHintsParams}, the response is of type + --- {@link InlayHint InlayHint[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlayHint = 'textDocument/inlayHint', + --- A request to provide inline completions in a document. The request's parameter is of + --- type {@link InlineCompletionParams}, the response is of type + --- {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. + --- @since 3.18.0 + textDocument_inlineCompletion = 'textDocument/inlineCompletion', + --- A request to provide inline values in a document. The request's parameter is of + --- type {@link InlineValueParams}, the response is of type + --- {@link InlineValue InlineValue[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlineValue = 'textDocument/inlineValue', + --- A request to provide ranges that can be edited together. + --- @since 3.16.0 + textDocument_linkedEditingRange = 'textDocument/linkedEditingRange', + --- A request to get the moniker of a symbol at a given text document position. + --- The request parameter is of type {@link TextDocumentPositionParams}. + --- The response is of type {@link Moniker Moniker[]} or `null`. + textDocument_moniker = 'textDocument/moniker', + --- A request to format a document on type. + textDocument_onTypeFormatting = 'textDocument/onTypeFormatting', + --- A request to result a `CallHierarchyItem` in a document at a given position. + --- Can be used as an input to an incoming or outgoing call hierarchy. + --- @since 3.16.0 + textDocument_prepareCallHierarchy = 'textDocument/prepareCallHierarchy', + --- A request to test and perform the setup necessary for a rename. + --- @since 3.16 - support for default behavior + textDocument_prepareRename = 'textDocument/prepareRename', + --- A request to result a `TypeHierarchyItem` in a document at a given position. + --- Can be used as an input to a subtypes or supertypes type hierarchy. + --- @since 3.17.0 + textDocument_prepareTypeHierarchy = 'textDocument/prepareTypeHierarchy', --- A request to format a range in a document. textDocument_rangeFormatting = 'textDocument/rangeFormatting', --- A request to format ranges in a document. --- @since 3.18.0 --- @proposed textDocument_rangesFormatting = 'textDocument/rangesFormatting', - --- A request to format a document on type. - textDocument_onTypeFormatting = 'textDocument/onTypeFormatting', + --- A request to resolve project-wide references for the symbol denoted + --- by the given text document position. The request's parameter is of + --- type {@link ReferenceParams} the response is of type + --- {@link Location Location[]} or a Thenable that resolves to such. + textDocument_references = 'textDocument/references', --- A request to rename a symbol. textDocument_rename = 'textDocument/rename', - --- A request to test and perform the setup necessary for a rename. - --- @since 3.16 - support for default behavior - textDocument_prepareRename = 'textDocument/prepareRename', - --- The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. - workspace_workspaceFolders = 'workspace/workspaceFolders', + --- A request to provide selection ranges in a document. The request's + --- parameter is of type {@link SelectionRangeParams}, the + --- response is of type {@link SelectionRange SelectionRange[]} or a Thenable + --- that resolves to such. + textDocument_selectionRange = 'textDocument/selectionRange', + --- @since 3.16.0 + textDocument_semanticTokens_full = 'textDocument/semanticTokens/full', + --- @since 3.16.0 + textDocument_semanticTokens_full_delta = 'textDocument/semanticTokens/full/delta', + --- @since 3.16.0 + textDocument_semanticTokens_range = 'textDocument/semanticTokens/range', + textDocument_signatureHelp = 'textDocument/signatureHelp', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_typeDefinition = 'textDocument/typeDefinition', + --- A document will save request is sent from the client to the server before + --- the document is actually saved. The request can return an array of TextEdits + --- which will be applied to the text document before it is saved. Please note that + --- clients might drop results if computing the text edits took too long or if a + --- server constantly fails on this request. This is done to keep the save fast and + --- reliable. + textDocument_willSaveWaitUntil = 'textDocument/willSaveWaitUntil', + --- A request to resolve the subtypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_subtypes = 'typeHierarchy/subtypes', + --- A request to resolve the supertypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_supertypes = 'typeHierarchy/supertypes', + --- A request to show a document. This request might open an + --- external program depending on the value of the URI to open. + --- For example a request to open `https://code.visualstudio.com/` + --- will very likely open the URI in a WEB browser. + --- @since 3.16.0 + window_showDocument = 'window/showDocument', + --- The show message request is sent from the server to the client to show a message + --- and a set of options actions to the user. + window_showMessageRequest = 'window/showMessageRequest', + --- The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress + --- reporting from the server. + window_workDoneProgress_create = 'window/workDoneProgress/create', + --- A request to resolve the range inside the workspace + --- symbol's location. + --- @since 3.17.0 + workspaceSymbol_resolve = 'workspaceSymbol/resolve', + --- A request sent from the server to the client to modified certain resources. + workspace_applyEdit = 'workspace/applyEdit', + --- A request to refresh all code actions + --- @since 3.16.0 + workspace_codeLens_refresh = 'workspace/codeLens/refresh', --- The 'workspace/configuration' request is sent from the server to the client to fetch a certain --- configuration setting. --- This pull model replaces the old push model were the client signaled configuration change via an @@ -1092,33 +1142,21 @@ protocol.Methods = { --- result of `workspace/configuration` requests) the server should register for an empty configuration --- change event and empty the cache if such an event is received. workspace_configuration = 'workspace/configuration', - --- @since 3.16.0 - workspace_semanticTokens_refresh = 'workspace/semanticTokens/refresh', - --- The will create files request is sent from the client to the server before files are actually - --- created as long as the creation is triggered from within the client. - --- The request can return a `WorkspaceEdit` which will be applied to workspace before the - --- files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file - --- to be created. - --- @since 3.16.0 - workspace_willCreateFiles = 'workspace/willCreateFiles', - --- The will rename files request is sent from the client to the server before files are actually - --- renamed as long as the rename is triggered from within the client. - --- @since 3.16.0 - workspace_willRenameFiles = 'workspace/willRenameFiles', - --- The did delete files notification is sent from the client to the server when - --- files were deleted from within the client. - --- @since 3.16.0 - workspace_willDeleteFiles = 'workspace/willDeleteFiles', - --- @since 3.17.0 - workspace_inlineValue_refresh = 'workspace/inlineValue/refresh', - --- @since 3.17.0 - workspace_inlayHint_refresh = 'workspace/inlayHint/refresh', --- The workspace diagnostic request definition. --- @since 3.17.0 workspace_diagnostic = 'workspace/diagnostic', --- The diagnostic refresh request definition. --- @since 3.17.0 workspace_diagnostic_refresh = 'workspace/diagnostic/refresh', + --- A request send from the client to the server to execute a command. The request might return + --- a workspace edit which the client will apply to the workspace. + workspace_executeCommand = 'workspace/executeCommand', + --- @since 3.17.0 + workspace_inlayHint_refresh = 'workspace/inlayHint/refresh', + --- @since 3.17.0 + workspace_inlineValue_refresh = 'workspace/inlineValue/refresh', + --- @since 3.16.0 + workspace_semanticTokens_refresh = 'workspace/semanticTokens/refresh', --- A request to list project-wide symbols matching the query string given --- by the {@link WorkspaceSymbolParams}. The response is --- of type {@link SymbolInformation SymbolInformation[]} or a Thenable that @@ -1127,61 +1165,23 @@ protocol.Methods = { --- need to advertise support for WorkspaceSymbols via the client capability --- `workspace.symbol.resolveSupport`. workspace_symbol = 'workspace/symbol', - --- A request to refresh all code actions - --- @since 3.16.0 - workspace_codeLens_refresh = 'workspace/codeLens/refresh', - --- A request send from the client to the server to execute a command. The request might return - --- a workspace edit which the client will apply to the workspace. - workspace_executeCommand = 'workspace/executeCommand', - --- A request sent from the server to the client to modified certain resources. - workspace_applyEdit = 'workspace/applyEdit', - --- The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress - --- reporting from the server. - window_workDoneProgress_create = 'window/workDoneProgress/create', - --- A request to resolve the incoming calls for a given `CallHierarchyItem`. + --- The will create files request is sent from the client to the server before files are actually + --- created as long as the creation is triggered from within the client. + --- The request can return a `WorkspaceEdit` which will be applied to workspace before the + --- files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file + --- to be created. --- @since 3.16.0 - callHierarchy_incomingCalls = 'callHierarchy/incomingCalls', - --- A request to resolve the outgoing calls for a given `CallHierarchyItem`. + workspace_willCreateFiles = 'workspace/willCreateFiles', + --- The did delete files notification is sent from the client to the server when + --- files were deleted from within the client. --- @since 3.16.0 - callHierarchy_outgoingCalls = 'callHierarchy/outgoingCalls', - --- A request to show a document. This request might open an - --- external program depending on the value of the URI to open. - --- For example a request to open `https://code.visualstudio.com/` - --- will very likely open the URI in a WEB browser. + workspace_willDeleteFiles = 'workspace/willDeleteFiles', + --- The will rename files request is sent from the client to the server before files are actually + --- renamed as long as the rename is triggered from within the client. --- @since 3.16.0 - window_showDocument = 'window/showDocument', - --- A request to resolve the supertypes for a given `TypeHierarchyItem`. - --- @since 3.17.0 - typeHierarchy_supertypes = 'typeHierarchy/supertypes', - --- A request to resolve the subtypes for a given `TypeHierarchyItem`. - --- @since 3.17.0 - typeHierarchy_subtypes = 'typeHierarchy/subtypes', - --- A request to resolve additional properties for an inlay hint. - --- The request's parameter is of type {@link InlayHint}, the response is - --- of type {@link InlayHint} or a Thenable that resolves to such. - --- @since 3.17.0 - inlayHint_resolve = 'inlayHint/resolve', - --- The show message request is sent from the server to the client to show a message - --- and a set of options actions to the user. - window_showMessageRequest = 'window/showMessageRequest', - --- Request to resolve additional information for a given completion item.The request's - --- parameter is of type {@link CompletionItem} the response - --- is of type {@link CompletionItem} or a Thenable that resolves to such. - completionItem_resolve = 'completionItem/resolve', - --- Request to resolve additional information for a given code action.The request's - --- parameter is of type {@link CodeAction} the response - --- is of type {@link CodeAction} or a Thenable that resolves to such. - codeAction_resolve = 'codeAction/resolve', - --- A request to resolve the range inside the workspace - --- symbol's location. - --- @since 3.17.0 - workspaceSymbol_resolve = 'workspaceSymbol/resolve', - --- A request to resolve a command for a given code lens. - codeLens_resolve = 'codeLens/resolve', - --- Request to resolve additional information for a given document link. The request's - --- parameter is of type {@link DocumentLink} the response - --- is of type {@link DocumentLink} or a Thenable that resolves to such. - documentLink_resolve = 'documentLink/resolve', + workspace_willRenameFiles = 'workspace/willRenameFiles', + --- The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. + workspace_workspaceFolders = 'workspace/workspaceFolders', } local function freeze(t) return setmetatable({}, { diff --git a/runtime/lua/vim/lsp/types/protocol.lua b/runtime/lua/vim/lsp/types/protocol.lua index 241d64e6e5..e1ed8dbcc3 100644 --- a/runtime/lua/vim/lsp/types/protocol.lua +++ b/runtime/lua/vim/lsp/types/protocol.lua @@ -1,7 +1,7 @@ --[[ -This file is autogenerated from scripts/lsp_types.lua +This file is autogenerated from scripts/gen_lsp.lua Regenerate: -nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/protocol.lua +nvim -l scripts/gen_lsp.lua gen --version 3.18 --runtime/lua/vim/lsp/types/protocol.lua --]] ---@alias lsp.null nil @@ -611,16 +611,12 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---A parameter literal used in inline completion requests. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams ---Additional information about the context in which inline completions were ---requested. ---@field context lsp.InlineCompletionContext ---Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. ---- ----@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionList ---The inline completion items ---@field items lsp.InlineCompletionItem[] @@ -628,10 +624,11 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionItem ---The text to replace the range with. Must be set. ----@field insertText string|lsp.StringValue +---@field insertText string +---The format of the insert text. The format applies to the `insertText`. If omitted defaults to `InsertTextFormat.PlainText`. +---@field insertTextFormat? lsp.InsertTextFormat ---A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. ---@field filterText? string ---The range to replace. Must begin and end on the same line. @@ -642,7 +639,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Inline completion options used during static or dynamic registration. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionRegistrationOptions: lsp.InlineCompletionOptions, lsp.StaticRegistrationOptions ---@class lsp.RegistrationParams @@ -1249,6 +1245,18 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Registration options for a {@link DocumentRangeFormattingRequest}. ---@class lsp.DocumentRangeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions +---The parameters of a {@link DocumentRangesFormattingRequest}. +--- +---@since 3.18.0 +---@proposed +---@class lsp.DocumentRangesFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The ranges to format +---@field ranges lsp.Range[] +---The format options +---@field options lsp.FormattingOptions + ---The parameters of a {@link DocumentOnTypeFormattingRequest}. ---@class lsp.DocumentOnTypeFormattingParams ---The document to format. @@ -1904,36 +1912,18 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Provides information about the context in which an inline completion was requested. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionContext ---Describes how the inline completion was triggered. ---@field triggerKind lsp.InlineCompletionTriggerKind ---Provides information about the currently selected item in the autocomplete widget if it is visible. ---@field selectedCompletionInfo? lsp.SelectedCompletionInfo ----A string value used as a snippet is a template which allows to insert text ----and to control the editor cursor when insertion happens. ---- ----A snippet can define tab stops and placeholders with `$1`, `$2` ----and `${3:foo}`. `$0` defines the final tab stop, it defaults to ----the end of the snippet. Variables are defined with `$name` and ----`${name:default value}`. ---- ----@since 3.18.0 ----@proposed ----@class lsp.StringValue ----The kind of string value. ----@field kind "snippet" ----The snippet string. ----@field value string - ---Inline completion options used during static registration. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionOptions ----General parameters to register for a notification or to register a provider. +---General parameters to to register for an notification or to register a provider. ---@class lsp.Registration ---The id used to register the request. The id can be used to deregister ---the request again. @@ -2104,7 +2094,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Inline completion options used during static registration. --- ---@since 3.18.0 ----@proposed ---@field inlineCompletionProvider? boolean|lsp.InlineCompletionOptions ---Workspace specific server capabilities. ---@field workspace? anonym12 @@ -2399,6 +2388,11 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Provider options for a {@link DocumentRangeFormattingRequest}. ---@class lsp.DocumentRangeFormattingOptions +---Whether the server supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean ---Provider options for a {@link DocumentOnTypeFormattingRequest}. ---@class lsp.DocumentOnTypeFormattingOptions @@ -2548,7 +2542,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Describes the currently selected completion item. --- ---@since 3.18.0 ----@proposed ---@class lsp.SelectedCompletionInfo ---The range that will be replaced if this completion item is accepted. ---@field range lsp.Range @@ -2857,7 +2850,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Client capabilities specific to inline completions. --- ---@since 3.18.0 ----@proposed ---@field inlineCompletion? lsp.InlineCompletionClientCapabilities ---Capabilities specific to the notebook document support. @@ -3283,6 +3275,11 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---@class lsp.DocumentRangeFormattingClientCapabilities ---Whether range formatting supports dynamic registration. ---@field dynamicRegistration? boolean +---Whether the client supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean ---Client capabilities of a {@link DocumentOnTypeFormattingRequest}. ---@class lsp.DocumentOnTypeFormattingClientCapabilities @@ -3474,7 +3471,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Client capabilities specific to inline completions. --- ---@since 3.18.0 ----@proposed ---@class lsp.InlineCompletionClientCapabilities ---Whether implementation supports dynamic registration for inline completion providers. ---@field dynamicRegistration? boolean @@ -3663,6 +3659,12 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---| 1 # Type ---| 2 # Parameter +---Defines whether the insert text in a completion item should be interpreted as +---plain text or a snippet. +---@alias lsp.InsertTextFormat +---| 1 # PlainText +---| 2 # Snippet + ---The message type ---@alias lsp.MessageType ---| 1 # Error @@ -3718,12 +3720,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---@alias lsp.CompletionItemTag ---| 1 # Deprecated ----Defines whether the insert text in a completion item should be interpreted as ----plain text or a snippet. ----@alias lsp.InsertTextFormat ----| 1 # PlainText ----| 2 # Snippet - ---How whitespace and indentation is handled during completion ---item insertion. --- @@ -3767,7 +3763,6 @@ nvim -l scripts/lsp_types.lua gen --version 3.1x --runtime/lua/vim/lsp/types/pro ---Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. --- ---@since 3.18.0 ----@proposed ---@alias lsp.InlineCompletionTriggerKind ---| 0 # Invoked ---| 1 # Automatic -- cgit From 214b125132778c5d51d4d7e673d31a9be835e150 Mon Sep 17 00:00:00 2001 From: Raphael Date: Thu, 3 Aug 2023 17:52:21 +0800 Subject: fix(gen_lsp.lua): no notifications in lsp.Methods #24530 Problem: - Notifications are missing from `lsp.Methods`. - Need a way to represent `$/` prefixed methods. Solution: - Generate notifications. - Use "dollar_" prefix for `$/` methods. --- runtime/lua/vim/lsp/protocol.lua | 86 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 3844c697c6..0755fa991f 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -954,22 +954,46 @@ protocol.Methods = { --- parameter is of type {@link DocumentLink} the response --- is of type {@link DocumentLink} or a Thenable that resolves to such. documentLink_resolve = 'documentLink/resolve', + dollar_cancelRequest = '$/cancelRequest', + dollar_logTrace = '$/logTrace', + dollar_progress = '$/progress', + dollar_setTrace = '$/setTrace', + --- The exit event is sent from the client to the server to + --- ask the server to exit its process. + exit = 'exit', --- The initialize request is sent from the client to the server. --- It is sent once as the request after starting up the server. --- The requests parameter is of type {@link InitializeParams} --- the response if of type {@link InitializeResult} of a Thenable that --- resolves to such. initialize = 'initialize', + --- The initialized notification is sent from the client to the + --- server after the client is fully initialized and the server + --- is allowed to send requests from the server to the client. + initialized = 'initialized', --- A request to resolve additional properties for an inlay hint. --- The request's parameter is of type {@link InlayHint}, the response is --- of type {@link InlayHint} or a Thenable that resolves to such. --- @since 3.17.0 inlayHint_resolve = 'inlayHint/resolve', + notebookDocument_didChange = 'notebookDocument/didChange', + --- A notification sent when a notebook closes. + --- @since 3.17.0 + notebookDocument_didClose = 'notebookDocument/didClose', + --- A notification sent when a notebook opens. + --- @since 3.17.0 + notebookDocument_didOpen = 'notebookDocument/didOpen', + --- A notification sent when a notebook document is saved. + --- @since 3.17.0 + notebookDocument_didSave = 'notebookDocument/didSave', --- A shutdown request is sent from the client to the server. --- It is sent once when the client decides to shutdown the --- server. The only notification that is sent after a shutdown request --- is the exit event. shutdown = 'shutdown', + --- The telemetry event notification is sent from the server to the client to ask + --- the client to log telemetry data. + telemetry_event = 'telemetry/event', --- A request to provide commands for the given text document and range. textDocument_codeAction = 'textDocument/codeAction', --- A request to provide code lens for the given text document. @@ -1003,6 +1027,29 @@ protocol.Methods = { --- The document diagnostic request definition. --- @since 3.17.0 textDocument_diagnostic = 'textDocument/diagnostic', + --- The document change notification is sent from the client to the server to signal + --- changes to a text document. + textDocument_didChange = 'textDocument/didChange', + --- The document close notification is sent from the client to the server when + --- the document got closed in the client. The document's truth now exists where + --- the document's uri points to (e.g. if the document's uri is a file uri the + --- truth now exists on disk). As with the open notification the close notification + --- is about managing the document's content. Receiving a close notification + --- doesn't mean that the document was open in an editor before. A close + --- notification requires a previous open notification to be sent. + textDocument_didClose = 'textDocument/didClose', + --- The document open notification is sent from the client to the server to signal + --- newly opened text documents. The document's truth is now managed by the client + --- and the server must not try to read the document's truth using the document's + --- uri. Open in this sense means it is managed by the client. It doesn't necessarily + --- mean that its content is presented in an editor. An open notification must not + --- be sent more than once without a corresponding close notification send before. + --- This means open and close notification must be balanced and the max open count + --- is one. + textDocument_didOpen = 'textDocument/didOpen', + --- The document save notification is sent from the client to the server when + --- the document got saved in the client. + textDocument_didSave = 'textDocument/didSave', --- A request to list all color symbols found in a given text document. The request's --- parameter is of type {@link DocumentColorParams} the --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable @@ -1025,7 +1072,7 @@ protocol.Methods = { --- response is of type {@link FoldingRangeList} or a Thenable --- that resolves to such. textDocument_foldingRange = 'textDocument/foldingRange', - --- A request to format a whole document. + --- A request to to format a whole document. textDocument_formatting = 'textDocument/formatting', --- Request to request hover information at a given text document position. The request's --- parameter is of type {@link TextDocumentPosition} the response is of @@ -1071,6 +1118,9 @@ protocol.Methods = { --- Can be used as an input to a subtypes or supertypes type hierarchy. --- @since 3.17.0 textDocument_prepareTypeHierarchy = 'textDocument/prepareTypeHierarchy', + --- Diagnostics notification are sent from the server to the client to signal + --- results of validation runs. + textDocument_publishDiagnostics = 'textDocument/publishDiagnostics', --- A request to format a range in a document. textDocument_rangeFormatting = 'textDocument/rangeFormatting', --- A request to format ranges in a document. @@ -1101,6 +1151,9 @@ protocol.Methods = { --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a --- Thenable that resolves to such. textDocument_typeDefinition = 'textDocument/typeDefinition', + --- A document will save notification is sent from the client to the server before + --- the document is actually saved. + textDocument_willSave = 'textDocument/willSave', --- A document will save request is sent from the client to the server before --- the document is actually saved. The request can return an array of TextEdits --- which will be applied to the text document before it is saved. Please note that @@ -1114,15 +1167,24 @@ protocol.Methods = { --- A request to resolve the supertypes for a given `TypeHierarchyItem`. --- @since 3.17.0 typeHierarchy_supertypes = 'typeHierarchy/supertypes', + --- The log message notification is sent from the server to the client to ask + --- the client to log a particular message. + window_logMessage = 'window/logMessage', --- A request to show a document. This request might open an --- external program depending on the value of the URI to open. --- For example a request to open `https://code.visualstudio.com/` --- will very likely open the URI in a WEB browser. --- @since 3.16.0 window_showDocument = 'window/showDocument', + --- The show message notification is sent from a server to a client to ask + --- the client to display a particular message in the user interface. + window_showMessage = 'window/showMessage', --- The show message request is sent from the server to the client to show a message --- and a set of options actions to the user. window_showMessageRequest = 'window/showMessageRequest', + --- The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress + --- initiated on the server side. + window_workDoneProgress_cancel = 'window/workDoneProgress/cancel', --- The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress --- reporting from the server. window_workDoneProgress_create = 'window/workDoneProgress/create', @@ -1148,6 +1210,28 @@ protocol.Methods = { --- The diagnostic refresh request definition. --- @since 3.17.0 workspace_diagnostic_refresh = 'workspace/diagnostic/refresh', + --- The configuration change notification is sent from the client to the server + --- when the client's configuration has changed. The notification contains + --- the changed configuration as defined by the language client. + workspace_didChangeConfiguration = 'workspace/didChangeConfiguration', + --- The watched files notification is sent from the client to the server when + --- the client detects changes to file watched by the language client. + workspace_didChangeWatchedFiles = 'workspace/didChangeWatchedFiles', + --- The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace + --- folder configuration changes. + workspace_didChangeWorkspaceFolders = 'workspace/didChangeWorkspaceFolders', + --- The did create files notification is sent from the client to the server when + --- files were created from within the client. + --- @since 3.16.0 + workspace_didCreateFiles = 'workspace/didCreateFiles', + --- The will delete files request is sent from the client to the server before files are actually + --- deleted as long as the deletion is triggered from within the client. + --- @since 3.16.0 + workspace_didDeleteFiles = 'workspace/didDeleteFiles', + --- The did rename files notification is sent from the client to the server when + --- files were renamed from within the client. + --- @since 3.16.0 + workspace_didRenameFiles = 'workspace/didRenameFiles', --- A request send from the client to the server to execute a command. The request might return --- a workspace edit which the client will apply to the workspace. workspace_executeCommand = 'workspace/executeCommand', -- cgit From f1772272b4fda43c093fc495f54b5e7c11968d62 Mon Sep 17 00:00:00 2001 From: Raphael Date: Thu, 3 Aug 2023 19:03:48 +0800 Subject: refactor(lsp): use protocol.Methods instead of strings #24537 --- runtime/lua/vim/lsp/_watchfiles.lua | 3 +- runtime/lua/vim/lsp/buf.lua | 54 ++++++++++++------------- runtime/lua/vim/lsp/codelens.lua | 5 ++- runtime/lua/vim/lsp/diagnostic.lua | 9 +++-- runtime/lua/vim/lsp/handlers.lua | 71 +++++++++++++++++---------------- runtime/lua/vim/lsp/inlay_hint.lua | 15 +++---- runtime/lua/vim/lsp/semantic_tokens.lua | 5 ++- runtime/lua/vim/lsp/tagfunc.lua | 5 ++- 8 files changed, 87 insertions(+), 80 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index b66f2f6f32..c271dc6e14 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -1,6 +1,7 @@ local bit = require('bit') local watch = require('vim._watch') local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods local lpeg = vim.lpeg local M = {} @@ -190,7 +191,7 @@ function M.register(reg, ctx) if not queue_timers[client_id] then queue_timers[client_id] = vim.defer_fn(function() - client.notify('workspace/didChangeWatchedFiles', { + client.notify(ms.workspace_didChangeWatchedFiles, { changes = change_queues[client_id], }) queue_timers[client_id] = nil diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 5e0e429021..59afaf6fa0 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -2,6 +2,7 @@ local api = vim.api local validate = vim.validate local util = require('vim.lsp.util') local npcall = vim.F.npcall +local ms = require('vim.lsp.protocol').Methods local M = {} @@ -41,7 +42,7 @@ end --- window. Calling the function twice will jump into the floating window. function M.hover() local params = util.make_position_params() - request('textDocument/hover', params) + request(ms.textDocument_hover, params) end local function request_with_options(name, params, options) @@ -64,7 +65,7 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.declaration(options) local params = util.make_position_params() - request_with_options('textDocument/declaration', params, options) + request_with_options(ms.textDocument_declaration, params, options) end --- Jumps to the definition of the symbol under the cursor. @@ -74,7 +75,7 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.definition(options) local params = util.make_position_params() - request_with_options('textDocument/definition', params, options) + request_with_options(ms.textDocument_definition, params, options) end --- Jumps to the definition of the type of the symbol under the cursor. @@ -84,7 +85,7 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.type_definition(options) local params = util.make_position_params() - request_with_options('textDocument/typeDefinition', params, options) + request_with_options(ms.textDocument_typeDefinition, params, options) end --- Lists all the implementations for the symbol under the cursor in the @@ -94,14 +95,14 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.implementation(options) local params = util.make_position_params() - request_with_options('textDocument/implementation', params, options) + request_with_options(ms.textDocument_implementation, params, options) end --- Displays signature information about the symbol under the cursor in a --- floating window. function M.signature_help() local params = util.make_position_params() - request('textDocument/signatureHelp', params) + request(ms.textDocument_signatureHelp, params) end --- Retrieves the completion items at the current cursor position. Can only be @@ -115,7 +116,7 @@ end function M.completion(context) local params = util.make_position_params() params.context = context - return request('textDocument/completion', params) + return request(ms.textDocument_completion, params) end ---@param bufnr integer @@ -199,7 +200,7 @@ function M.format(options) if not range and mode == 'v' or mode == 'V' then range = range_from_selection(bufnr, mode) end - local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' + local method = range and ms.textDocument_rangeFormatting or ms.textDocument_formatting local clients = vim.lsp.get_clients({ id = options.id, @@ -270,7 +271,7 @@ function M.rename(new_name, options) bufnr = bufnr, name = options.name, -- Clients must at least support rename, prepareRename is optional - method = 'textDocument/rename', + method = ms.textDocument_rename, }) if options.filter then clients = vim.tbl_filter(options.filter, clients) @@ -305,17 +306,17 @@ function M.rename(new_name, options) local function rename(name) local params = util.make_position_params(win, client.offset_encoding) params.newName = name - local handler = client.handlers['textDocument/rename'] - or vim.lsp.handlers['textDocument/rename'] - client.request('textDocument/rename', params, function(...) + local handler = client.handlers[ms.textDocument_rename] + or vim.lsp.handlers[ms.textDocument_rename] + client.request(ms.textDocument_rename, params, function(...) handler(...) try_use_client(next(clients, idx)) end, bufnr) end - if client.supports_method('textDocument/prepareRename') then + if client.supports_method(ms.textDocument_prepareRename) then local params = util.make_position_params(win, client.offset_encoding) - client.request('textDocument/prepareRename', params, function(err, result) + client.request(ms.textDocument_prepareRename, params, function(err, result) if err or result == nil then if next(clients, idx) then try_use_client(next(clients, idx)) @@ -354,7 +355,7 @@ function M.rename(new_name, options) end, bufnr) else assert( - client.supports_method('textDocument/rename'), + client.supports_method(ms.textDocument_rename), 'Client must support textDocument/rename' ) if new_name then @@ -390,7 +391,7 @@ function M.references(context, options) params.context = context or { includeDeclaration = true, } - request_with_options('textDocument/references', params, options) + request_with_options(ms.textDocument_references, params, options) end --- Lists all symbols in the current buffer in the quickfix window. @@ -399,7 +400,7 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.document_symbol(options) local params = { textDocument = util.make_text_document_params() } - request_with_options('textDocument/documentSymbol', params, options) + request_with_options(ms.textDocument_documentSymbol, params, options) end local function pick_call_hierarchy_item(call_hierarchy_items) @@ -423,7 +424,7 @@ end local function call_hierarchy(method) local params = util.make_position_params() - request('textDocument/prepareCallHierarchy', params, function(err, result, ctx) + request(ms.textDocument_prepareCallHierarchy, params, function(err, result, ctx) if err then vim.notify(err.message, vim.log.levels.WARN) return @@ -496,7 +497,7 @@ function M.add_workspace_folder(workspace_folder) end end if not found then - client.notify('workspace/didChangeWorkspaceFolders', params) + client.notify(ms.workspace_didChangeWorkspaceFolders, params) if not client.workspace_folders then client.workspace_folders = {} end @@ -524,7 +525,7 @@ function M.remove_workspace_folder(workspace_folder) for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do for idx, folder in pairs(client.workspace_folders) do if folder.name == workspace_folder then - client.notify('workspace/didChangeWorkspaceFolders', params) + client.notify(ms.workspace_didChangeWorkspaceFolders, params) client.workspace_folders[idx] = nil return end @@ -548,7 +549,7 @@ function M.workspace_symbol(query, options) return end local params = { query = query } - request_with_options('workspace/symbol', params, options) + request_with_options(ms.workspace_symbol, params, options) end --- Send request to the server to resolve document highlights for the current @@ -567,7 +568,7 @@ end --- |hl-LspReferenceWrite| function M.document_highlight() local params = util.make_position_params() - request('textDocument/documentHighlight', params) + request(ms.textDocument_documentHighlight, params) end --- Removes document highlights from current buffer. @@ -655,7 +656,7 @@ local function on_code_action_results(results, ctx, options) local client = vim.lsp.get_client_by_id(action_tuple[1]) local action = action_tuple[2] - local reg = client.dynamic_capabilities:get('textDocument/codeAction', { bufnr = ctx.bufnr }) + local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = ctx.bufnr }) local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') or client.supports_method('codeAction/resolve') @@ -694,9 +695,8 @@ end --- with all aggregated results local function code_action_request(params, options) local bufnr = api.nvim_get_current_buf() - local method = 'textDocument/codeAction' - vim.lsp.buf_request_all(bufnr, method, params, function(results) - local ctx = { bufnr = bufnr, method = method, params = params } + vim.lsp.buf_request_all(bufnr, ms.textDocument_codeAction, params, function(results) + local ctx = { bufnr = bufnr, method = ms.textDocument_codeAction, params = params } on_code_action_results(results, ctx, options) end) end @@ -776,7 +776,7 @@ function M.execute_command(command_params) arguments = command_params.arguments, workDoneToken = command_params.workDoneToken, } - request('workspace/executeCommand', command_params) + request(ms.workspace_executeCommand, command_params) end return M diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index a516238ae0..d581eb985f 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -1,5 +1,6 @@ local util = require('vim.lsp.util') local log = require('vim.lsp.log') +local ms = require('vim.lsp.protocol').Methods local api = vim.api local M = {} @@ -33,7 +34,7 @@ local function execute_lens(lens, bufnr, client_id) local client = vim.lsp.get_client_by_id(client_id) assert(client, 'Client is required to execute lens, client_id=' .. client_id) client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) - vim.lsp.handlers['workspace/executeCommand'](...) + vim.lsp.handlers[ms.workspace_executeCommand](...) M.refresh() end) end @@ -267,7 +268,7 @@ function M.refresh() return end active_refreshes[bufnr] = true - vim.lsp.buf_request(0, 'textDocument/codeLens', params, M.on_codelens) + vim.lsp.buf_request(0, ms.textDocument_codeLens, params, M.on_codelens) end return M diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 44bb90d985..a0568bc09c 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -2,6 +2,7 @@ local util = require('vim.lsp.util') local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods local api = vim.api @@ -422,13 +423,13 @@ function M._enable(bufnr) buffer = bufnr, callback = function(opts) if - opts.data.method ~= 'textDocument/didChange' - and opts.data.method ~= 'textDocument/didOpen' + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen then return end if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh('textDocument/diagnostic', { bufnr = bufnr, only_visible = true }) + util._refresh(ms.textDocument_diagnostic, { bufnr = bufnr, only_visible = true }) end end, group = augroup, @@ -437,7 +438,7 @@ function M._enable(bufnr) api.nvim_buf_attach(bufnr, false, { on_reload = function() if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh('textDocument/diagnostic', { bufnr = bufnr }) + util._refresh(ms.textDocument_diagnostic, { bufnr = bufnr }) end end, on_detach = function() diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index d887183972..6fe4b7f939 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -1,5 +1,6 @@ local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods local util = require('vim.lsp.util') local api = vim.api @@ -15,14 +16,14 @@ local function err_message(...) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand -M['workspace/executeCommand'] = function(_, _, _, _) +M[ms.workspace_executeCommand] = function(_, _, _, _) -- Error handling is done implicitly by wrapping all handlers; see end of this file end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress ---@param result lsp.ProgressParams ---@param ctx lsp.HandlerContext -M['$/progress'] = function(_, result, ctx) +M[ms.dollar_progress] = function(_, result, ctx) local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') @@ -58,7 +59,7 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create ---@param result lsp.WorkDoneProgressCreateParams ---@param ctx lsp.HandlerContext -M['window/workDoneProgress/create'] = function(_, result, ctx) +M[ms.window_workDoneProgress_create] = function(_, result, ctx) local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') @@ -70,7 +71,7 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessageRequest ---@param result lsp.ShowMessageRequestParams -M['window/showMessageRequest'] = function(_, result) +M[ms.window_showMessageRequest] = function(_, result) local actions = result.actions or {} local co, is_main = coroutine.running() if co and not is_main then @@ -105,7 +106,7 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, result, ctx) +M[ms.client_registerCapability] = function(_, result, ctx) local client_id = ctx.client_id ---@type lsp.Client local client = vim.lsp.get_client_by_id(client_id) @@ -118,7 +119,7 @@ M['client/registerCapability'] = function(_, result, ctx) ---@type string[] local unsupported = {} for _, reg in ipairs(result.registrations) do - if reg.method == 'workspace/didChangeWatchedFiles' then + if reg.method == ms.workspace_didChangeWatchedFiles then require('vim.lsp._watchfiles').register(reg, ctx) elseif not client.dynamic_capabilities:supports_registration(reg.method) then unsupported[#unsupported + 1] = reg.method @@ -136,13 +137,13 @@ M['client/registerCapability'] = function(_, result, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability -M['client/unregisterCapability'] = function(_, result, ctx) +M[ms.client_unregisterCapability] = function(_, result, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) client.dynamic_capabilities:unregister(result.unregisterations) for _, unreg in ipairs(result.unregisterations) do - if unreg.method == 'workspace/didChangeWatchedFiles' then + if unreg.method == ms.workspace_didChangeWatchedFiles then require('vim.lsp._watchfiles').unregister(unreg, ctx) end end @@ -150,7 +151,7 @@ M['client/unregisterCapability'] = function(_, result, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit -M['workspace/applyEdit'] = function(_, workspace_edit, ctx) +M[ms.workspace_applyEdit] = function(_, workspace_edit, ctx) assert( workspace_edit, 'workspace/applyEdit must be called with `ApplyWorkspaceEditParams`. Server is violating the specification' @@ -170,7 +171,7 @@ M['workspace/applyEdit'] = function(_, workspace_edit, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_configuration -M['workspace/configuration'] = function(_, result, ctx) +M[ms.workspace_configuration] = function(_, result, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) if not client then @@ -200,7 +201,7 @@ M['workspace/configuration'] = function(_, result, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders -M['workspace/workspaceFolders'] = function(_, _, ctx) +M[ms.workspace_workspaceFolders] = function(_, _, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) if not client then @@ -210,24 +211,24 @@ M['workspace/workspaceFolders'] = function(_, _, ctx) return client.workspace_folders or vim.NIL end -M['textDocument/publishDiagnostics'] = function(...) +M[ms.textDocument_publishDiagnostics] = function(...) return require('vim.lsp.diagnostic').on_publish_diagnostics(...) end -M['textDocument/diagnostic'] = function(...) +M[ms.textDocument_diagnostic] = function(...) return require('vim.lsp.diagnostic').on_diagnostic(...) end -M['textDocument/codeLens'] = function(...) +M[ms.textDocument_codeLens] = function(...) return require('vim.lsp.codelens').on_codelens(...) end -M['textDocument/inlayHint'] = function(...) +M[ms.textDocument_inlayHint] = function(...) return require('vim.lsp.inlay_hint').on_inlayhint(...) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references -M['textDocument/references'] = function(_, result, ctx, config) +M[ms.textDocument_references] = function(_, result, ctx, config) if not result or vim.tbl_isempty(result) then vim.notify('No references found') else @@ -283,7 +284,7 @@ local function response_to_list(map_result, entity, title_fn) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol -M['textDocument/documentSymbol'] = response_to_list( +M[ms.textDocument_documentSymbol] = response_to_list( util.symbols_to_items, 'document symbols', function(ctx) @@ -293,12 +294,12 @@ M['textDocument/documentSymbol'] = response_to_list( ) --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol -M['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols', function(ctx) +M[ms.workspace_symbol] = response_to_list(util.symbols_to_items, 'symbols', function(ctx) return string.format("Symbols matching '%s'", ctx.params.query) end) --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename -M['textDocument/rename'] = function(_, result, ctx, _) +M[ms.textDocument_rename] = function(_, result, ctx, _) if not result then vim.notify("Language server couldn't provide rename result", vim.log.levels.INFO) return @@ -308,7 +309,7 @@ M['textDocument/rename'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting -M['textDocument/rangeFormatting'] = function(_, result, ctx, _) +M[ms.textDocument_rangeFormatting] = function(_, result, ctx, _) if not result then return end @@ -317,7 +318,7 @@ M['textDocument/rangeFormatting'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting -M['textDocument/formatting'] = function(_, result, ctx, _) +M[ms.textDocument_formatting] = function(_, result, ctx, _) if not result then return end @@ -326,7 +327,7 @@ M['textDocument/formatting'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -M['textDocument/completion'] = function(_, result, _, _) +M[ms.textDocument_completion] = function(_, result, _, _) if vim.tbl_isempty(result or {}) then return end @@ -380,7 +381,7 @@ function M.hover(_, result, ctx, config) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover -M['textDocument/hover'] = M.hover +M[ms.textDocument_hover] = M.hover --- Jumps to a location. Used as a handler for multiple LSP methods. ---@param _ nil not used @@ -420,13 +421,13 @@ local function location_handler(_, result, ctx, config) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration -M['textDocument/declaration'] = location_handler +M[ms.textDocument_declaration] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition -M['textDocument/definition'] = location_handler +M[ms.textDocument_definition] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition -M['textDocument/typeDefinition'] = location_handler +M[ms.textDocument_typeDefinition] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation -M['textDocument/implementation'] = location_handler +M[ms.textDocument_implementation] = location_handler --- |lsp-handler| for the method "textDocument/signatureHelp". --- The active parameter is highlighted with |hl-LspSignatureActiveParameter|. @@ -477,10 +478,10 @@ function M.signature_help(_, result, ctx, config) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp -M['textDocument/signatureHelp'] = M.signature_help +M[ms.textDocument_signatureHelp] = M.signature_help --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight -M['textDocument/documentHighlight'] = function(_, result, ctx, _) +M[ms.textDocument_documentHighlight] = function(_, result, ctx, _) if not result then return end @@ -523,13 +524,13 @@ local make_call_hierarchy_handler = function(direction) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls -M['callHierarchy/incomingCalls'] = make_call_hierarchy_handler('from') +M[ms.callHierarchy_incomingCalls] = make_call_hierarchy_handler('from') --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls -M['callHierarchy/outgoingCalls'] = make_call_hierarchy_handler('to') +M[ms.callHierarchy_outgoingCalls] = make_call_hierarchy_handler('to') --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_logMessage -M['window/logMessage'] = function(_, result, ctx, _) +M[ms.window_logMessage] = function(_, result, ctx, _) local message_type = result.type local message = result.message local client_id = ctx.client_id @@ -551,7 +552,7 @@ M['window/logMessage'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessage -M['window/showMessage'] = function(_, result, ctx, _) +M[ms.window_showMessage] = function(_, result, ctx, _) local message_type = result.type local message = result.message local client_id = ctx.client_id @@ -570,7 +571,7 @@ M['window/showMessage'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument -M['window/showDocument'] = function(_, result, ctx, _) +M[ms.window_showDocument] = function(_, result, ctx, _) local uri = result.uri if result.external then @@ -611,7 +612,7 @@ M['window/showDocument'] = function(_, result, ctx, _) end ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh -M['workspace/inlayHint/refresh'] = function(err, result, ctx, config) +M[ms.workspace_inlayHint_refresh] = function(err, result, ctx, config) return require('vim.lsp.inlay_hint').on_refresh(err, result, ctx, config) end diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 2bf0fb9cb2..eb2f59b312 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -1,5 +1,6 @@ local util = require('vim.lsp.util') local log = require('vim.lsp.log') +local ms = require('vim.lsp.protocol').Methods local api = vim.api local M = {} @@ -87,7 +88,7 @@ function M.on_refresh(err, _, ctx, _) if api.nvim_win_get_buf(winid) == bufnr then local bufstate = bufstates[bufnr] if bufstate then - util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) break end end @@ -143,24 +144,24 @@ local function enable(bufnr) buffer = bufnr, callback = function(opts) if - opts.data.method ~= 'textDocument/didChange' - and opts.data.method ~= 'textDocument/didOpen' + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen then return end if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) end end, group = augroup, }) - util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) api.nvim_buf_attach(bufnr, false, { on_reload = function(_, cb_bufnr) clear(cb_bufnr) if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then bufstates[cb_bufnr].applied = {} - util._refresh('textDocument/inlayHint', { bufnr = cb_bufnr }) + util._refresh(ms.textDocument_inlayHint, { bufnr = cb_bufnr }) end end, on_detach = function(_, cb_bufnr) @@ -176,7 +177,7 @@ local function enable(bufnr) }) else bufstate.enabled = true - util._refresh('textDocument/inlayHint', { bufnr = bufnr }) + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) end end diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 84723bbc05..bab1b23ee4 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -1,6 +1,7 @@ local api = vim.api local bit = require('bit') local handlers = require('vim.lsp.handlers') +local ms = require('vim.lsp.protocol').Methods local util = require('vim.lsp.util') local uv = vim.uv @@ -292,7 +293,7 @@ function STHighlighter:send_request() local hasEditProvider = type(spec) == 'table' and spec.delta local params = { textDocument = util.make_text_document_params(self.bufnr) } - local method = 'textDocument/semanticTokens/full' + local method = ms.textDocument_semanticTokens_full if hasEditProvider and current_result.result_id then method = method .. '/delta' @@ -755,7 +756,7 @@ end --- the BufWinEnter event should take care of it next time it's displayed. --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#semanticTokens_refreshRequest -handlers['workspace/semanticTokens/refresh'] = function(err, _, ctx) +handlers[ms.workspace_semanticTokens_refresh] = function(err, _, ctx) if err then return vim.NIL end diff --git a/runtime/lua/vim/lsp/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index c70eb573c2..957449743b 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -1,5 +1,6 @@ local lsp = vim.lsp local util = lsp.util +local ms = lsp.protocol.Methods local function mk_tag_item(name, range, uri, offset_encoding) local bufnr = vim.uri_to_bufnr(uri) @@ -14,7 +15,7 @@ end local function query_definition(pattern) local params = util.make_position_params() - local results_by_client, err = lsp.buf_request_sync(0, 'textDocument/definition', params, 1000) + local results_by_client, err = lsp.buf_request_sync(0, ms.textDocument_definition, params, 1000) if err then return {} end @@ -42,7 +43,7 @@ end local function query_workspace_symbols(pattern) local results_by_client, err = - lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000) + lsp.buf_request_sync(0, ms.workspace_symbol, { query = pattern }, 1000) if err then return {} end -- cgit From cc87dda31a5b5637ade7ddcfe5199f2df5fd47df Mon Sep 17 00:00:00 2001 From: Sean Dewar Date: Fri, 4 Aug 2023 07:10:54 +0100 Subject: fix(lsp): do not assume client capability exists in watchfiles check (#24550) PR #23689 assumes `client.config.capabilities.workspace.didChangeWatchedFiles` exists when checking `dynamicRegistration`, but thats's true only if it was passed to `vim.lsp.start{_client}`. This caused #23806 (still an issue in v0.9.1; needs manual backport), but #23681 fixed it by defaulting `config.capabilities` to `make_client_capabilities` if not passed to `vim.lsp.start{_client}`. However, the bug resurfaces on HEAD if you provide a non-nil `capabilities` to `vim.lsp.start{_client}` with missing fields (e.g: not made via `make_client_capabilities`). From what I see, the spec says such missing fields should be interpreted as an absence of the capability (including those indicated by missing sub-fields): https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#clientCapabilities Also, suggest `vim.empty_dict()` for an empty dict in `:h vim.lsp.start_client()` (`{[vim.type_idx]=vim.types.dictionary}` no longer works anyway, probably since the cjson switch). --- runtime/lua/vim/lsp/_watchfiles.lua | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index c271dc6e14..5dbd4a7199 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -121,12 +121,15 @@ M._poll_exclude_pattern = parse('**/.git/{objects,subtree-cache}/**') function M.register(reg, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) - if - -- Ill-behaved servers may not honor the client capability and try to register - -- anyway, so ignore requests when the user has opted out of the feature. - not client.config.capabilities.workspace.didChangeWatchedFiles.dynamicRegistration - or not client.workspace_folders - then + -- Ill-behaved servers may not honor the client capability and try to register + -- anyway, so ignore requests when the user has opted out of the feature. + local has_capability = vim.tbl_get( + client.config.capabilities or {}, + 'workspace', + 'didChangeWatchedFiles', + 'dynamicRegistration' + ) + if not has_capability or not client.workspace_folders then return end local watch_regs = {} --- @type table -- cgit From 42630923fc00633d806af97c1792b2ed4a71e1cc Mon Sep 17 00:00:00 2001 From: Raphael Date: Sat, 5 Aug 2023 17:03:57 +0800 Subject: refactor(lsp): use protocol.Methods instead of strings #24570 --- runtime/lua/vim/lsp/buf.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 59afaf6fa0..3b1654d11f 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -446,14 +446,14 @@ end --- |quickfix| window. If the symbol can resolve to multiple --- items, the user can pick one in the |inputlist()|. function M.incoming_calls() - call_hierarchy('callHierarchy/incomingCalls') + call_hierarchy(ms.callHierarchy_incomingCalls) end --- Lists all the items that are called by the symbol under the --- cursor in the |quickfix| window. If the symbol can resolve to --- multiple items, the user can pick one in the |inputlist()|. function M.outgoing_calls() - call_hierarchy('callHierarchy/outgoingCalls') + call_hierarchy(ms.callHierarchy_outgoingCalls) end --- List workspace folders. @@ -659,10 +659,10 @@ local function on_code_action_results(results, ctx, options) local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = ctx.bufnr }) local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') - or client.supports_method('codeAction/resolve') + or client.supports_method(ms.codeAction_resolve) if not action.edit and client and supports_resolve then - client.request('codeAction/resolve', action, function(err, resolved_action) + client.request(ms.codeAction_resolve, action, function(err, resolved_action) if err then vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) return -- cgit From 832459219b4cbf3151e48b43187f1ab0c94ea285 Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Mon, 7 Aug 2023 06:35:06 -0700 Subject: docs(lsp): fix references to protocol.constants #24578 --- runtime/lua/vim/lsp/buf.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 3b1654d11f..6cd0aa1e95 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -112,7 +112,7 @@ end --- about the context in which a completion was triggered (how it was triggered, --- and by which trigger character, if applicable) --- ----@see vim.lsp.protocol.constants.CompletionTriggerKind +---@see vim.lsp.protocol.CompletionTriggerKind function M.completion(context) local params = util.make_position_params() params.context = context @@ -728,7 +728,7 @@ end --- using mark-like indexing. See |api-indexing| --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction ----@see vim.lsp.protocol.constants.CodeActionTriggerKind +---@see vim.lsp.protocol.CodeActionTriggerKind function M.code_action(options) validate({ options = { options, 't', true } }) options = options or {} -- cgit From c43c745a14dced87a23227d7be4f1c33d4455193 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 9 Aug 2023 11:06:13 +0200 Subject: fix(lua): improve annotations for stricter luals diagnostics (#24609) Problem: luals returns stricter diagnostics with bundled luarc.json Solution: Improve some function and type annotations: * use recognized uv.* types * disable diagnostic for global `vim` in shared.lua * docs: don't start comment lines with taglink (otherwise LuaLS will interpret it as a type) * add type alias for lpeg pattern * fix return annotation for `vim.secure.trust` * rename local Range object in vim.version (shadows `Range` in vim.treesitter) * fix some "missing fields" warnings * add missing required fields for test functions in eval.lua * rename lsp meta files for consistency --- runtime/lua/vim/lsp/_meta.lua | 22 + runtime/lua/vim/lsp/_meta/protocol.lua | 4396 +++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/_watchfiles.lua | 8 +- runtime/lua/vim/lsp/inlay_hint.lua | 4 +- runtime/lua/vim/lsp/semantic_tokens.lua | 13 +- runtime/lua/vim/lsp/types.lua | 21 - runtime/lua/vim/lsp/types/protocol.lua | 4393 ------------------------------ runtime/lua/vim/lsp/util.lua | 4 +- 8 files changed, 4433 insertions(+), 4428 deletions(-) create mode 100644 runtime/lua/vim/lsp/_meta.lua create mode 100644 runtime/lua/vim/lsp/_meta/protocol.lua delete mode 100644 runtime/lua/vim/lsp/types.lua delete mode 100644 runtime/lua/vim/lsp/types/protocol.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_meta.lua b/runtime/lua/vim/lsp/_meta.lua new file mode 100644 index 0000000000..acf799264e --- /dev/null +++ b/runtime/lua/vim/lsp/_meta.lua @@ -0,0 +1,22 @@ +---@meta +error('Cannot require a meta file') + +---@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil): any? + +---@class lsp.HandlerContext +---@field method string +---@field client_id integer +---@field bufnr? integer +---@field params? any + +---@class lsp.ResponseError +---@field code integer +---@field message string +---@field data string|number|boolean|table[]|table|nil + +--- @class lsp.DocumentFilter +--- @field language? string +--- @field scheme? string +--- @field pattern? string + +--- @alias lsp.RegisterOptions any | lsp.StaticRegistrationOptions | lsp.TextDocumentRegistrationOptions diff --git a/runtime/lua/vim/lsp/_meta/protocol.lua b/runtime/lua/vim/lsp/_meta/protocol.lua new file mode 100644 index 0000000000..72b0f00f65 --- /dev/null +++ b/runtime/lua/vim/lsp/_meta/protocol.lua @@ -0,0 +1,4396 @@ +--[[ +This file is autogenerated from scripts/gen_lsp.lua +Regenerate: +nvim -l scripts/gen_lsp.lua gen --version 3.18 --runtime/lua/vim/lsp/_meta/protocol.lua +--]] + +---@meta +error('Cannot require a meta file') + +---@alias lsp.null nil +---@alias uinteger integer +---@alias lsp.decimal number +---@alias lsp.DocumentUri string +---@alias lsp.URI string +---@alias lsp.LSPObject table +---@alias lsp.LSPArray lsp.LSPAny[] +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|number|boolean|nil + +---@class lsp.ImplementationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Represents a location inside a resource, such as a line +---inside a text file. +---@class lsp.Location +---@field uri lsp.DocumentUri +---@field range lsp.Range + +---@class lsp.ImplementationRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.TypeDefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.TypeDefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---A workspace folder inside a client. +---@class lsp.WorkspaceFolder +---The associated URI for this workspace folder. +---@field uri lsp.URI +---The name of the workspace folder. Used to refer to this +---workspace folder in the user interface. +---@field name string + +---The parameters of a `workspace/didChangeWorkspaceFolders` notification. +---@class lsp.DidChangeWorkspaceFoldersParams +---The actual workspace folder change event. +---@field event lsp.WorkspaceFoldersChangeEvent + +---The parameters of a configuration request. +---@class lsp.ConfigurationParams +---@field items lsp.ConfigurationItem[] + +---Parameters for a {@link DocumentColorRequest}. +---@class lsp.DocumentColorParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a color range from a document. +---@class lsp.ColorInformation +---The range in the document where this color appears. +---@field range lsp.Range +---The actual color value for this color range. +---@field color lsp.Color + +---@class lsp.DocumentColorRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters for a {@link ColorPresentationRequest}. +---@class lsp.ColorPresentationParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The color to request presentations for. +---@field color lsp.Color +---The range where the color would be inserted. Serves as a context. +---@field range lsp.Range + +---@class lsp.ColorPresentation +---The label of this color presentation. It will be shown on the color +---picker header. By default this is also the text that is inserted when selecting +---this color presentation. +---@field label string +---An {@link TextEdit edit} which is applied to a document when selecting +---this presentation for the color. When `falsy` the {@link ColorPresentation.label label} +---is used. +---@field textEdit? lsp.TextEdit +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves. +---@field additionalTextEdits? lsp.TextEdit[] + +---@class lsp.WorkDoneProgressOptions +---@field workDoneProgress? boolean + +---General text document registration options. +---@class lsp.TextDocumentRegistrationOptions +---A document selector to identify the scope of the registration. If set to null +---the document selector provided on the client side will be used. +---@field documentSelector lsp.DocumentSelector|lsp.null + +---Parameters for a {@link FoldingRangeRequest}. +---@class lsp.FoldingRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a folding range. To be valid, start and end line must be bigger than zero and smaller +---than the number of lines in the document. Clients are free to ignore invalid ranges. +---@class lsp.FoldingRange +---The zero-based start line of the range to fold. The folded area starts after the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field startLine uinteger +---The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. +---@field startCharacter? uinteger +---The zero-based end line of the range to fold. The folded area ends with the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field endLine uinteger +---The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. +---@field endCharacter? uinteger +---Describes the kind of the folding range such as `comment' or 'region'. The kind +---is used to categorize folding ranges and used by commands like 'Fold all comments'. +---See {@link FoldingRangeKind} for an enumeration of standardized kinds. +---@field kind? lsp.FoldingRangeKind +---The text that the client should show when the specified range is +---collapsed. If not defined or not supported by the client, a default +---will be chosen by the client. +--- +---@since 3.17.0 +---@field collapsedText? string + +---@class lsp.FoldingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.DeclarationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.DeclarationRegistrationOptions: lsp.DeclarationOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in selection range requests. +---@class lsp.SelectionRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The positions inside the text document. +---@field positions lsp.Position[] + +---A selection range represents a part of a selection hierarchy. A selection range +---may have a parent selection range that contains it. +---@class lsp.SelectionRange +---The {@link Range range} of this selection range. +---@field range lsp.Range +---The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. +---@field parent? lsp.SelectionRange + +---@class lsp.SelectionRangeRegistrationOptions: lsp.SelectionRangeOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkDoneProgressCreateParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---@class lsp.WorkDoneProgressCancelParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---The parameter of a `textDocument/prepareCallHierarchy` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---Represents programming constructs like functions or constructors in the context +---of call hierarchy. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. +---Must be contained by the {@link CallHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a call hierarchy prepare and +---incoming calls or outgoing calls requests. +---@field data? lsp.LSPAny + +---Call hierarchy options used during static or dynamic registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `callHierarchy/incomingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an incoming call, e.g. a caller of a method or constructor. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCall +---The item that makes the call. +---@field from lsp.CallHierarchyItem +---The ranges at which the calls appear. This is relative to the caller +---denoted by {@link CallHierarchyIncomingCall.from `this.from`}. +---@field fromRanges lsp.Range[] + +---The parameter of a `callHierarchy/outgoingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCall +---The item that is called. +---@field to lsp.CallHierarchyItem +---The range at which this item is called. This is the range relative to the caller, e.g the item +---passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} +---and not {@link CallHierarchyOutgoingCall.to `this.to`}. +---@field fromRanges lsp.Range[] + +---@since 3.16.0 +---@class lsp.SemanticTokensParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---@since 3.16.0 +---@class lsp.SemanticTokens +---An optional result id. If provided and clients support delta updating +---the client will include the result id in the next semantic token request. +---A server can then instead of computing all semantic tokens again simply +---send a delta. +---@field resultId? string +---The actual tokens. +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensPartialResult +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The result id of a previous response. The result Id can either point to a full response +---or a delta response depending on what was received last. +---@field previousResultId string + +---@since 3.16.0 +---@class lsp.SemanticTokensDelta +---@field resultId? string +---The semantic token edits to transform a previous result into a new result. +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaPartialResult +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The range the semantic tokens are requested for. +---@field range lsp.Range + +---Params to show a resource in the UI. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentParams +---The uri to show. +---@field uri lsp.URI +---Indicates to show the resource in an external program. +---To show, for example, `https://code.visualstudio.com/` +---in the default WEB browser set `external` to `true`. +---@field external? boolean +---An optional property to indicate whether the editor +---showing the document should take focus or not. +---Clients might ignore this property if an external +---program is started. +---@field takeFocus? boolean +---An optional selection range if the document is a text +---document. Clients might ignore the property if an +---external program is started or the file is not a text +---file. +---@field selection? lsp.Range + +---The result of a showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentResult +---A boolean indicating if the show was successful. +---@field success boolean + +---@class lsp.LinkedEditingRangeParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRanges +---A list of ranges that can be edited together. The ranges must have +---identical length and contain identical text content. The ranges cannot overlap. +---@field ranges lsp.Range[] +---An optional word pattern (regular expression) that describes valid contents for +---the given ranges. If no pattern is provided, the client configuration's word +---pattern will be used. +---@field wordPattern? string + +---@class lsp.LinkedEditingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameters sent in notifications/requests for user-initiated creation of +---files. +--- +---@since 3.16.0 +---@class lsp.CreateFilesParams +---An array of all files/folders created in this operation. +---@field files lsp.FileCreate[] + +---A workspace edit represents changes to many resources managed in the workspace. The edit +---should either provide `changes` or `documentChanges`. If documentChanges are present +---they are preferred over `changes` if the client can handle versioned document edits. +--- +---Since version 3.13.0 a workspace edit can contain resource operations as well. If resource +---operations are present clients need to execute the operations in the order in which they +---are provided. So a workspace edit for example can consist of the following two changes: +---(1) a create file a.txt and (2) a text document edit which insert text into file a.txt. +--- +---An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will +---cause failure of the operation. How the client recovers from the failure is described by +---the client capability: `workspace.workspaceEdit.failureHandling` +---@class lsp.WorkspaceEdit +---Holds changes to existing resources. +---@field changes? table +---Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes +---are either an array of `TextDocumentEdit`s to express changes to n different text documents +---where each text document edit addresses a specific version of a text document. Or it can contain +---above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. +--- +---Whether a client supports versioned document edits is expressed via +---`workspace.workspaceEdit.documentChanges` client capability. +--- +---If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then +---only plain `TextEdit`s using the `changes` property are supported. +---@field documentChanges? lsp.TextDocumentEdit|lsp.CreateFile|lsp.RenameFile|lsp.DeleteFile[] +---A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and +---delete file / folder operations. +--- +---Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. +--- +---@since 3.16.0 +---@field changeAnnotations? table + +---The options to register for file operations. +--- +---@since 3.16.0 +---@class lsp.FileOperationRegistrationOptions +---The actual filters. +---@field filters lsp.FileOperationFilter[] + +---The parameters sent in notifications/requests for user-initiated renames of +---files. +--- +---@since 3.16.0 +---@class lsp.RenameFilesParams +---An array of all files/folders renamed in this operation. When a folder is renamed, only +---the folder will be included, and not its children. +---@field files lsp.FileRename[] + +---The parameters sent in notifications/requests for user-initiated deletes of +---files. +--- +---@since 3.16.0 +---@class lsp.DeleteFilesParams +---An array of all files/folders deleted in this operation. +---@field files lsp.FileDelete[] + +---@class lsp.MonikerParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Moniker definition to match LSIF 0.5 moniker definition. +--- +---@since 3.16.0 +---@class lsp.Moniker +---The scheme of the moniker. For example tsc or .Net +---@field scheme string +---The identifier of the moniker. The value is opaque in LSIF however +---schema owners are allowed to define the structure if they want. +---@field identifier string +---The scope in which the moniker is unique +---@field unique lsp.UniquenessLevel +---The moniker kind if known. +---@field kind? lsp.MonikerKind + +---@class lsp.MonikerRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameter of a `textDocument/prepareTypeHierarchy` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---@since 3.17.0 +---@class lsp.TypeHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace +---but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being +---picked, e.g. the name of a function. Must be contained by the +---{@link TypeHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a type hierarchy prepare and +---supertypes or subtypes requests. It could also be used to identify the +---type hierarchy in the server, helping improve the performance on +---resolving supertypes and subtypes. +---@field data? lsp.LSPAny + +---Type hierarchy options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `typeHierarchy/supertypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySupertypesParams +---@field item lsp.TypeHierarchyItem + +---The parameter of a `typeHierarchy/subtypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySubtypesParams +---@field item lsp.TypeHierarchyItem + +---A parameter literal used in inline value requests. +--- +---@since 3.17.0 +---@class lsp.InlineValueParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inline values should be computed. +---@field range lsp.Range +---Additional information about the context in which inline values were +---requested. +---@field context lsp.InlineValueContext + +---Inline value options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueRegistrationOptions: lsp.InlineValueOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in inlay hint requests. +--- +---@since 3.17.0 +---@class lsp.InlayHintParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inlay hints should be computed. +---@field range lsp.Range + +---Inlay hint information. +--- +---@since 3.17.0 +---@class lsp.InlayHint +---The position of this hint. +---@field position lsp.Position +---The label of this hint. A human readable string or an array of +---InlayHintLabelPart label parts. +--- +---*Note* that neither the string nor the label part can be empty. +---@field label string|lsp.InlayHintLabelPart[] +---The kind of this hint. Can be omitted in which case the client +---should fall back to a reasonable default. +---@field kind? lsp.InlayHintKind +---Optional text edits that are performed when accepting this inlay hint. +--- +---*Note* that edits are expected to change the document so that the inlay +---hint (or its nearest variant) is now part of the document and the inlay +---hint itself is now obsolete. +---@field textEdits? lsp.TextEdit[] +---The tooltip text when you hover over this item. +---@field tooltip? string|lsp.MarkupContent +---Render padding before the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingLeft? boolean +---Render padding after the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingRight? boolean +---A data entry field that is preserved on an inlay hint between +---a `textDocument/inlayHint` and a `inlayHint/resolve` request. +---@field data? lsp.LSPAny + +---Inlay hint options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintRegistrationOptions: lsp.InlayHintOptions, lsp.StaticRegistrationOptions + +---Parameters of the document diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The additional identifier provided during registration. +---@field identifier? string +---The result id of a previous response if provided. +---@field previousResultId? string + +---A partial result for a document diagnostic report. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticReportPartialResult +---@field relatedDocuments table + +---Cancellation data returned from a diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DiagnosticServerCancellationData +---@field retriggerRequest boolean + +---Diagnostic registration options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters of the workspace diagnostic request. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticParams +---The additional identifier provided during registration. +---@field identifier? string +---The currently known diagnostic reports with their +---previous result ids. +---@field previousResultIds lsp.PreviousResultId[] + +---A workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReport +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---A partial result for a workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReportPartialResult +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---The params sent in an open notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidOpenNotebookDocumentParams +---The notebook document that got opened. +---@field notebookDocument lsp.NotebookDocument +---The text documents that represent the content +---of a notebook cell. +---@field cellTextDocuments lsp.TextDocumentItem[] + +---The params sent in a change notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidChangeNotebookDocumentParams +---The notebook document that did change. The version number points +---to the version after all provided changes have been applied. If +---only the text document content of a cell changes the notebook version +---doesn't necessarily have to change. +---@field notebookDocument lsp.VersionedNotebookDocumentIdentifier +---The actual changes to the notebook document. +--- +---The changes describe single state changes to the notebook document. +---So if there are two changes c1 (at array index 0) and c2 (at array +---index 1) for a notebook in state S then c1 moves the notebook from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and +---c2 is computed on the state S'. +--- +---To mirror the content of a notebook using change events use the following approach: +---- start with the same initial content +---- apply the 'notebookDocument/didChange' notifications in the order you receive them. +---- apply the `NotebookChangeEvent`s in a single notification in the order +--- you receive them. +---@field change lsp.NotebookDocumentChangeEvent + +---The params sent in a save notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidSaveNotebookDocumentParams +---The notebook document that got saved. +---@field notebookDocument lsp.NotebookDocumentIdentifier + +---The params sent in a close notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidCloseNotebookDocumentParams +---The notebook document that got closed. +---@field notebookDocument lsp.NotebookDocumentIdentifier +---The text documents that represent the content +---of a notebook cell that got closed. +---@field cellTextDocuments lsp.TextDocumentIdentifier[] + +---A parameter literal used in inline completion requests. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---Additional information about the context in which inline completions were +---requested. +---@field context lsp.InlineCompletionContext + +---Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. +---@class lsp.InlineCompletionList +---The inline completion items +---@field items lsp.InlineCompletionItem[] + +---An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionItem +---The text to replace the range with. Must be set. +---@field insertText string +---The format of the insert text. The format applies to the `insertText`. If omitted defaults to `InsertTextFormat.PlainText`. +---@field insertTextFormat? lsp.InsertTextFormat +---A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. +---@field filterText? string +---The range to replace. Must begin and end on the same line. +---@field range? lsp.Range +---An optional {@link Command} that is executed *after* inserting this completion. +---@field command? lsp.Command + +---Inline completion options used during static or dynamic registration. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionRegistrationOptions: lsp.InlineCompletionOptions, lsp.StaticRegistrationOptions + +---@class lsp.RegistrationParams +---@field registrations lsp.Registration[] + +---@class lsp.UnregistrationParams +---@field unregisterations lsp.Unregistration[] + +---@class lsp.InitializeParams: lsp._InitializeParams + +---The result returned from an initialize request. +---@class lsp.InitializeResult +---The capabilities the language server provides. +---@field capabilities lsp.ServerCapabilities +---Information about the server. +--- +---@since 3.15.0 +---@field serverInfo? anonym1 + +---The data type of the ResponseError if the +---initialize request fails. +---@class lsp.InitializeError +---Indicates whether the client execute the following retry logic: +---(1) show the message provided by the ResponseError to the user +---(2) user selects retry or cancel +---(3) if user selected retry the initialize method is sent again. +---@field retry boolean + +---@class lsp.InitializedParams + +---The parameters of a change configuration notification. +---@class lsp.DidChangeConfigurationParams +---The actual changed settings +---@field settings lsp.LSPAny + +---@class lsp.DidChangeConfigurationRegistrationOptions +---@field section? string|string[] + +---The parameters of a notification message. +---@class lsp.ShowMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---@class lsp.ShowMessageRequestParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string +---The message action items to present. +---@field actions? lsp.MessageActionItem[] + +---@class lsp.MessageActionItem +---A short title like 'Retry', 'Open Log' etc. +---@field title string + +---The log message parameters. +---@class lsp.LogMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---The parameters sent in an open text document notification +---@class lsp.DidOpenTextDocumentParams +---The document that was opened. +---@field textDocument lsp.TextDocumentItem + +---The change text document notification's parameters. +---@class lsp.DidChangeTextDocumentParams +---The document that did change. The version number points +---to the version after all provided content changes have +---been applied. +---@field textDocument lsp.VersionedTextDocumentIdentifier +---The actual content changes. The content changes describe single state changes +---to the document. So if there are two content changes c1 (at array index 0) and +---c2 (at array index 1) for a document in state S then c1 moves the document from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed +---on the state S'. +--- +---To mirror the content of a document using change events use the following approach: +---- start with the same initial content +---- apply the 'textDocument/didChange' notifications in the order you receive them. +---- apply the `TextDocumentContentChangeEvent`s in a single notification in the order +--- you receive them. +---@field contentChanges lsp.TextDocumentContentChangeEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.TextDocumentChangeRegistrationOptions: lsp.TextDocumentRegistrationOptions +---How documents are synced to the server. +---@field syncKind lsp.TextDocumentSyncKind + +---The parameters sent in a close text document notification +---@class lsp.DidCloseTextDocumentParams +---The document that was closed. +---@field textDocument lsp.TextDocumentIdentifier + +---The parameters sent in a save text document notification +---@class lsp.DidSaveTextDocumentParams +---The document that was saved. +---@field textDocument lsp.TextDocumentIdentifier +---Optional the content when saved. Depends on the includeText value +---when the save notification was requested. +---@field text? string + +---Save registration options. +---@class lsp.TextDocumentSaveRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters sent in a will save text document notification. +---@class lsp.WillSaveTextDocumentParams +---The document that will be saved. +---@field textDocument lsp.TextDocumentIdentifier +---The 'TextDocumentSaveReason'. +---@field reason lsp.TextDocumentSaveReason + +---A text edit applicable to a text document. +---@class lsp.TextEdit +---The range of the text document to be manipulated. To insert +---text into a document create a range where start === end. +---@field range lsp.Range +---The string to be inserted. For delete operations use an +---empty string. +---@field newText string + +---The watched files change notification's parameters. +---@class lsp.DidChangeWatchedFilesParams +---The actual file events. +---@field changes lsp.FileEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.DidChangeWatchedFilesRegistrationOptions +---The watchers to register. +---@field watchers lsp.FileSystemWatcher[] + +---The publish diagnostic notification's parameters. +---@class lsp.PublishDiagnosticsParams +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---Optional the version number of the document the diagnostics are published for. +--- +---@since 3.15.0 +---@field version? integer +---An array of diagnostic information items. +---@field diagnostics lsp.Diagnostic[] + +---Completion parameters +---@class lsp.CompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---The completion context. This is only available it the client specifies +---to send this using the client capability `textDocument.completion.contextSupport === true` +---@field context? lsp.CompletionContext + +---A completion item represents a text snippet that is +---proposed to complete text that is being typed. +---@class lsp.CompletionItem +---The label of this completion item. +--- +---The label property is also by default the text that +---is inserted when selecting this completion. +--- +---If label details are provided the label itself should +---be an unqualified name of the completion item. +---@field label string +---Additional details for the label +--- +---@since 3.17.0 +---@field labelDetails? lsp.CompletionItemLabelDetails +---The kind of this completion item. Based of the kind +---an icon is chosen by the editor. +---@field kind? lsp.CompletionItemKind +---Tags for this completion item. +--- +---@since 3.15.0 +---@field tags? lsp.CompletionItemTag[] +---A human-readable string with additional information +---about this item, like type or symbol information. +---@field detail? string +---A human-readable string that represents a doc-comment. +---@field documentation? string|lsp.MarkupContent +---Indicates if this item is deprecated. +---@deprecated Use `tags` instead. +---@field deprecated? boolean +---Select this item when showing. +--- +---*Note* that only one completion item can be selected and that the +---tool / client decides which item that is. The rule is that the *first* +---item of those that match best is selected. +---@field preselect? boolean +---A string that should be used when comparing this item +---with other items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field sortText? string +---A string that should be used when filtering a set of +---completion items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field filterText? string +---A string that should be inserted into a document when selecting +---this completion. When `falsy` the {@link CompletionItem.label label} +---is used. +--- +---The `insertText` is subject to interpretation by the client side. +---Some tools might not take the string literally. For example +---VS Code when code complete is requested in this example +---`con` and a completion item with an `insertText` of +---`console` is provided it will only insert `sole`. Therefore it is +---recommended to use `textEdit` instead since it avoids additional client +---side interpretation. +---@field insertText? string +---The format of the insert text. The format applies to both the +---`insertText` property and the `newText` property of a provided +---`textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. +--- +---Please note that the insertTextFormat doesn't apply to +---`additionalTextEdits`. +---@field insertTextFormat? lsp.InsertTextFormat +---How whitespace and indentation is handled during completion +---item insertion. If not provided the clients default value depends on +---the `textDocument.completion.insertTextMode` client capability. +--- +---@since 3.16.0 +---@field insertTextMode? lsp.InsertTextMode +---An {@link TextEdit edit} which is applied to a document when selecting +---this completion. When an edit is provided the value of +---{@link CompletionItem.insertText insertText} is ignored. +--- +---Most editors support two different operations when accepting a completion +---item. One is to insert a completion text and the other is to replace an +---existing text with a completion text. Since this can usually not be +---predetermined by a server it can report both ranges. Clients need to +---signal support for `InsertReplaceEdits` via the +---`textDocument.completion.insertReplaceSupport` client capability +---property. +--- +---*Note 1:* The text edit's range as well as both ranges from an insert +---replace edit must be a [single line] and they must contain the position +---at which completion has been requested. +---*Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range +---must be a prefix of the edit's replace range, that means it must be +---contained and starting at the same position. +--- +---@since 3.16.0 additional type `InsertReplaceEdit` +---@field textEdit? lsp.TextEdit|lsp.InsertReplaceEdit +---The edit text used if the completion item is part of a CompletionList and +---CompletionList defines an item default for the text edit range. +--- +---Clients will only honor this property if they opt into completion list +---item defaults using the capability `completionList.itemDefaults`. +--- +---If not provided and a list's default range is provided the label +---property is used as a text. +--- +---@since 3.17.0 +---@field textEditText? string +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this completion. Edits must not overlap (including the same insert position) +---with the main {@link CompletionItem.textEdit edit} nor with themselves. +--- +---Additional text edits should be used to change text unrelated to the current cursor position +---(for example adding an import statement at the top of the file if the completion item will +---insert an unqualified type). +---@field additionalTextEdits? lsp.TextEdit[] +---An optional set of characters that when pressed while this completion is active will accept it first and +---then type that character. *Note* that all commit characters should have `length=1` and that superfluous +---characters will be ignored. +---@field commitCharacters? string[] +---An optional {@link Command command} that is executed *after* inserting this completion. *Note* that +---additional modifications to the current document should be described with the +---{@link CompletionItem.additionalTextEdits additionalTextEdits}-property. +---@field command? lsp.Command +---A data entry field that is preserved on a completion item between a +---{@link CompletionRequest} and a {@link CompletionResolveRequest}. +---@field data? lsp.LSPAny + +---Represents a collection of {@link CompletionItem completion items} to be presented +---in the editor. +---@class lsp.CompletionList +---This list it not complete. Further typing results in recomputing this list. +--- +---Recomputed lists have all their items replaced (not appended) in the +---incomplete completion sessions. +---@field isIncomplete boolean +---In many cases the items of an actual completion result share the same +---value for properties like `commitCharacters` or the range of a text +---edit. A completion list can therefore define item defaults which will +---be used if a completion item itself doesn't specify the value. +--- +---If a completion list specifies a default value and a completion item +---also specifies a corresponding value the one from the item is used. +--- +---Servers are only allowed to return default values if the client +---signals support for this via the `completionList.itemDefaults` +---capability. +--- +---@since 3.17.0 +---@field itemDefaults? anonym3 +---The completion items. +---@field items lsp.CompletionItem[] + +---Registration options for a {@link CompletionRequest}. +---@class lsp.CompletionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link HoverRequest}. +---@class lsp.HoverParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a hover request. +---@class lsp.Hover +---The hover's content +---@field contents lsp.MarkupContent|lsp.MarkedString|lsp.MarkedString[] +---An optional range inside the text document that is used to +---visualize the hover, e.g. by changing the background color. +---@field range? lsp.Range + +---Registration options for a {@link HoverRequest}. +---@class lsp.HoverRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---The signature help context. This is only available if the client specifies +---to send this using the client capability `textDocument.signatureHelp.contextSupport === true` +--- +---@since 3.15.0 +---@field context? lsp.SignatureHelpContext + +---Signature help represents the signature of something +---callable. There can be multiple signature but only one +---active and only one active parameter. +---@class lsp.SignatureHelp +---One or more signatures. +---@field signatures lsp.SignatureInformation[] +---The active signature. If omitted or the value lies outside the +---range of `signatures` the value defaults to zero or is ignored if +---the `SignatureHelp` has no signatures. +--- +---Whenever possible implementors should make an active decision about +---the active signature and shouldn't rely on a default value. +--- +---In future version of the protocol this property might become +---mandatory to better express this. +---@field activeSignature? uinteger +---The active parameter of the active signature. If omitted or the value +---lies outside the range of `signatures[activeSignature].parameters` +---defaults to 0 if the active signature has parameters. If +---the active signature has no parameters it is ignored. +---In future version of the protocol this property might become +---mandatory to better express the active parameter if the +---active signature does have any. +---@field activeParameter? uinteger + +---Registration options for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DefinitionRequest}. +---@class lsp.DefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Registration options for a {@link DefinitionRequest}. +---@class lsp.DefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link ReferencesRequest}. +---@class lsp.ReferenceParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---@field context lsp.ReferenceContext + +---Registration options for a {@link ReferencesRequest}. +---@class lsp.ReferenceRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---A document highlight is a range inside a text document which deserves +---special attention. Usually a document highlight is visualized by changing +---the background color of its range. +---@class lsp.DocumentHighlight +---The range this highlight applies to. +---@field range lsp.Range +---The highlight kind, default is {@link DocumentHighlightKind.Text text}. +---@field kind? lsp.DocumentHighlightKind + +---Registration options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents information about programming constructs like variables, classes, +---interfaces etc. +---@class lsp.SymbolInformation: lsp.BaseSymbolInformation +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The location of this symbol. The location's range is used by a tool +---to reveal the location in the editor. If the symbol is selected in the +---tool the range's start information is used to position the cursor. So +---the range usually spans more than the actual symbol's name and does +---normally include things like visibility modifiers. +--- +---The range doesn't have to denote a node range in the sense of an abstract +---syntax tree. It can therefore not be used to re-construct a hierarchy of +---the symbols. +---@field location lsp.Location + +---Represents programming constructs like variables, classes, interfaces etc. +---that appear in a document. Document symbols can be hierarchical and they +---have two ranges: one that encloses its definition and one that points to +---its most interesting range, e.g. the range of an identifier. +---@class lsp.DocumentSymbol +---The name of this symbol. Will be displayed in the user interface and therefore must not be +---an empty string or a string only consisting of white spaces. +---@field name string +---More detail for this symbol, e.g the signature of a function. +---@field detail? string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this document symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to determine if the clients cursor is +---inside the symbol to reveal in the symbol in the UI. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. +---Must be contained by the `range`. +---@field selectionRange lsp.Range +---Children of this symbol, e.g. properties of a class. +---@field children? lsp.DocumentSymbol[] + +---Registration options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link CodeActionRequest}. +---@class lsp.CodeActionParams +---The document in which the command was invoked. +---@field textDocument lsp.TextDocumentIdentifier +---The range for which the command was invoked. +---@field range lsp.Range +---Context carrying additional information. +---@field context lsp.CodeActionContext + +---Represents a reference to a command. Provides a title which +---will be used to represent a command in the UI and, optionally, +---an array of arguments which will be passed to the command handler +---function when invoked. +---@class lsp.Command +---Title of the command, like `save`. +---@field title string +---The identifier of the actual command handler. +---@field command string +---Arguments that the command handler should be +---invoked with. +---@field arguments? lsp.LSPAny[] + +---A code action represents a change that can be performed in code, e.g. to fix a problem or +---to refactor code. +--- +---A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. +---@class lsp.CodeAction +---A short, human-readable, title for this code action. +---@field title string +---The kind of the code action. +--- +---Used to filter code actions. +---@field kind? lsp.CodeActionKind +---The diagnostics that this code action resolves. +---@field diagnostics? lsp.Diagnostic[] +---Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted +---by keybindings. +--- +---A quick fix should be marked preferred if it properly addresses the underlying error. +---A refactoring should be marked preferred if it is the most reasonable choice of actions to take. +--- +---@since 3.15.0 +---@field isPreferred? boolean +---Marks that the code action cannot currently be applied. +--- +---Clients should follow the following guidelines regarding disabled code actions: +--- +--- - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) +--- code action menus. +--- +--- - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type +--- of code action, such as refactorings. +--- +--- - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) +--- that auto applies a code action and only disabled code actions are returned, the client should show the user an +--- error message with `reason` in the editor. +--- +---@since 3.16.0 +---@field disabled? anonym4 +---The workspace edit this code action performs. +---@field edit? lsp.WorkspaceEdit +---A command this code action executes. If a code action +---provides an edit and a command, first the edit is +---executed and then the command. +---@field command? lsp.Command +---A data entry field that is preserved on a code action between +---a `textDocument/codeAction` and a `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeActionRequest}. +---@class lsp.CodeActionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolParams +---A query string to filter symbols by. Clients may send an empty +---string here to request all symbols. +---@field query string + +---A special workspace symbol that supports locations without a range. +--- +---See also SymbolInformation. +--- +---@since 3.17.0 +---@class lsp.WorkspaceSymbol: lsp.BaseSymbolInformation +---The location of the symbol. Whether a server is allowed to +---return a location without a range depends on the client +---capability `workspace.symbol.resolveSupport`. +--- +---See SymbolInformation#location for more details. +---@field location lsp.Location|anonym5 +---A data entry field that is preserved on a workspace symbol between a +---workspace symbol request and a workspace symbol resolve request. +---@field data? lsp.LSPAny + +---Registration options for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolRegistrationOptions: lsp.WorkspaceSymbolOptions + +---The parameters of a {@link CodeLensRequest}. +---@class lsp.CodeLensParams +---The document to request code lens for. +---@field textDocument lsp.TextDocumentIdentifier + +---A code lens represents a {@link Command command} that should be shown along with +---source text, like the number of references, a way to run tests, etc. +--- +---A code lens is _unresolved_ when no command is associated to it. For performance +---reasons the creation of a code lens and resolving should be done in two stages. +---@class lsp.CodeLens +---The range in which this code lens is valid. Should only span a single line. +---@field range lsp.Range +---The command this code lens represents. +---@field command? lsp.Command +---A data entry field that is preserved on a code lens item between +---a {@link CodeLensRequest} and a [CodeLensResolveRequest] +---(#CodeLensResolveRequest) +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeLensRequest}. +---@class lsp.CodeLensRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkParams +---The document to provide document links for. +---@field textDocument lsp.TextDocumentIdentifier + +---A document link is a range in a text document that links to an internal or external resource, like another +---text document or a web site. +---@class lsp.DocumentLink +---The range this link applies to. +---@field range lsp.Range +---The uri this link points to. If missing a resolve request is sent later. +---@field target? lsp.URI +---The tooltip text when you hover over this link. +--- +---If a tooltip is provided, is will be displayed in a string that includes instructions on how to +---trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, +---user settings, and localization. +--- +---@since 3.15.0 +---@field tooltip? string +---A data entry field that is preserved on a document link between a +---DocumentLinkRequest and a DocumentLinkResolveRequest. +---@field data? lsp.LSPAny + +---Registration options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The format options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The range to format +---@field range lsp.Range +---The format options +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentRangesFormattingRequest}. +--- +---@since 3.18.0 +---@proposed +---@class lsp.DocumentRangesFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The ranges to format +---@field ranges lsp.Range[] +---The format options +---@field options lsp.FormattingOptions + +---The parameters of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The position around which the on type formatting should happen. +---This is not necessarily the exact position where the character denoted +---by the property `ch` got typed. +---@field position lsp.Position +---The character that has been typed that triggered the formatting +---on type request. That is not necessarily the last character that +---got inserted into the document since the client could auto insert +---characters as well (e.g. like automatic brace completion). +---@field ch string +---The formatting options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link RenameRequest}. +---@class lsp.RenameParams +---The document to rename. +---@field textDocument lsp.TextDocumentIdentifier +---The position at which this request was sent. +---@field position lsp.Position +---The new name of the symbol. If the given name is not valid the +---request must return a {@link ResponseError} with an +---appropriate message set. +---@field newName string + +---Registration options for a {@link RenameRequest}. +---@class lsp.RenameRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---@class lsp.PrepareRenameParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The parameters of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandParams +---The identifier of the actual command handler. +---@field command string +---Arguments that the command should be invoked with. +---@field arguments? lsp.LSPAny[] + +---Registration options for a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandRegistrationOptions: lsp.ExecuteCommandOptions + +---The parameters passed via an apply workspace edit request. +---@class lsp.ApplyWorkspaceEditParams +---An optional label of the workspace edit. This label is +---presented in the user interface for example on an undo +---stack to undo the workspace edit. +---@field label? string +---The edits to apply. +---@field edit lsp.WorkspaceEdit + +---The result returned from the apply workspace edit request. +--- +---@since 3.17 renamed from ApplyWorkspaceEditResponse +---@class lsp.ApplyWorkspaceEditResult +---Indicates whether the edit was applied or not. +---@field applied boolean +---An optional textual description for why the edit was not applied. +---This may be used by the server for diagnostic logging or to provide +---a suitable error for a request that triggered the edit. +---@field failureReason? string +---Depending on the client's failure handling strategy `failedChange` might +---contain the index of the change that failed. This property is only available +---if the client signals a `failureHandlingStrategy` in its client capabilities. +---@field failedChange? uinteger + +---@class lsp.WorkDoneProgressBegin +---@field kind "begin" +---Mandatory title of the progress operation. Used to briefly inform about +---the kind of operation being performed. +--- +---Examples: "Indexing" or "Linking dependencies". +---@field title string +---Controls if a cancel button should show to allow the user to cancel the +---long running operation. Clients that don't support cancellation are allowed +---to ignore the setting. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100]. +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressReport +---@field kind "report" +---Controls enablement state of a cancel button. +--- +---Clients that don't support cancellation or don't support controlling the button's +---enablement state are allowed to ignore the property. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100] +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressEnd +---@field kind "end" +---Optional, a final message indicating to for example indicate the outcome +---of the operation. +---@field message? string + +---@class lsp.SetTraceParams +---@field value lsp.TraceValues + +---@class lsp.LogTraceParams +---@field message string +---@field verbose? string + +---@class lsp.CancelParams +---The request id to cancel. +---@field id integer|string + +---@class lsp.ProgressParams +---The progress token provided by the client or server. +---@field token lsp.ProgressToken +---The progress data. +---@field value lsp.LSPAny + +---A parameter literal used in requests to pass a text document and a position inside that +---document. +---@class lsp.TextDocumentPositionParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The position inside the text document. +---@field position lsp.Position + +---@class lsp.WorkDoneProgressParams +---An optional token that a server can use to report work done progress. +---@field workDoneToken? lsp.ProgressToken + +---@class lsp.PartialResultParams +---An optional token that a server can use to report partial results (e.g. streaming) to +---the client. +---@field partialResultToken? lsp.ProgressToken + +---Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, +---including an origin range. +---@class lsp.LocationLink +---Span of the origin of this link. +--- +---Used as the underlined span for mouse interaction. Defaults to the word range at +---the definition position. +---@field originSelectionRange? lsp.Range +---The target resource identifier of this link. +---@field targetUri lsp.DocumentUri +---The full target range of this link. If the target for example is a symbol then target range is the +---range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to highlight the range in the editor. +---@field targetRange lsp.Range +---The range that should be selected and revealed when this link is being followed, e.g the name of a function. +---Must be contained by the `targetRange`. See also `DocumentSymbol#range` +---@field targetSelectionRange lsp.Range + +---A range in a text document expressed as (zero-based) start and end positions. +--- +---If you want to specify a range that contains a line including the line ending +---character(s) then use an end position denoting the start of the next line. +---For example: +---```ts +---{ +--- start: { line: 5, character: 23 } +--- end : { line 6, character : 0 } +---} +---``` +---@class lsp.Range +---The range's start position. +---@field start lsp.Position +---The range's end position. +---@field end lsp.Position + +---@class lsp.ImplementationOptions + +---Static registration options to be returned in the initialize +---request. +---@class lsp.StaticRegistrationOptions +---The id used to register the request. The id can be used to deregister +---the request again. See also Registration#id. +---@field id? string + +---@class lsp.TypeDefinitionOptions + +---The workspace folder change event. +---@class lsp.WorkspaceFoldersChangeEvent +---The array of added workspace folders +---@field added lsp.WorkspaceFolder[] +---The array of the removed workspace folders +---@field removed lsp.WorkspaceFolder[] + +---@class lsp.ConfigurationItem +---The scope to get the configuration section for. +---@field scopeUri? string +---The configuration section asked for. +---@field section? string + +---A literal to identify a text document in the client. +---@class lsp.TextDocumentIdentifier +---The text document's uri. +---@field uri lsp.DocumentUri + +---Represents a color in RGBA space. +---@class lsp.Color +---The red component of this color in the range [0-1]. +---@field red decimal +---The green component of this color in the range [0-1]. +---@field green decimal +---The blue component of this color in the range [0-1]. +---@field blue decimal +---The alpha component of this color in the range [0-1]. +---@field alpha decimal + +---@class lsp.DocumentColorOptions + +---@class lsp.FoldingRangeOptions + +---@class lsp.DeclarationOptions + +---Position in a text document expressed as zero-based line and character +---offset. Prior to 3.17 the offsets were always based on a UTF-16 string +---representation. So a string of the form `a𐐀b` the character offset of the +---character `a` is 0, the character offset of `𐐀` is 1 and the character +---offset of b is 3 since `𐐀` is represented using two code units in UTF-16. +---Since 3.17 clients and servers can agree on a different string encoding +---representation (e.g. UTF-8). The client announces it's supported encoding +---via the client capability [`general.positionEncodings`](#clientCapabilities). +---The value is an array of position encodings the client supports, with +---decreasing preference (e.g. the encoding at index `0` is the most preferred +---one). To stay backwards compatible the only mandatory encoding is UTF-16 +---represented via the string `utf-16`. The server can pick one of the +---encodings offered by the client and signals that encoding back to the +---client via the initialize result's property +---[`capabilities.positionEncoding`](#serverCapabilities). If the string value +---`utf-16` is missing from the client's capability `general.positionEncodings` +---servers can safely assume that the client supports UTF-16. If the server +---omits the position encoding in its initialize result the encoding defaults +---to the string value `utf-16`. Implementation considerations: since the +---conversion from one encoding into another requires the content of the +---file / line the conversion is best done where the file is read which is +---usually on the server side. +--- +---Positions are line end character agnostic. So you can not specify a position +---that denotes `\r|\n` or `\n|` where `|` represents the character offset. +--- +---@since 3.17.0 - support for negotiated position encoding. +---@class lsp.Position +---Line position in a document (zero-based). +--- +---If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. +---If a line number is negative, it defaults to 0. +---@field line uinteger +---Character offset on a line in a document (zero-based). +--- +---The meaning of this offset is determined by the negotiated +---`PositionEncodingKind`. +--- +---If the character value is greater than the line length it defaults back to the +---line length. +---@field character uinteger + +---@class lsp.SelectionRangeOptions + +---Call hierarchy options used during static registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensOptions +---The legend used by the server +---@field legend lsp.SemanticTokensLegend +---Server supports providing semantic tokens for a specific range +---of a document. +---@field range? boolean|anonym6 +---Server supports providing semantic tokens for a full document. +---@field full? boolean|anonym7 + +---@since 3.16.0 +---@class lsp.SemanticTokensEdit +---The start offset of the edit. +---@field start uinteger +---The count of elements to remove. +---@field deleteCount uinteger +---The elements to insert. +---@field data? uinteger[] + +---@class lsp.LinkedEditingRangeOptions + +---Represents information on a file/folder create. +--- +---@since 3.16.0 +---@class lsp.FileCreate +---A file:// URI for the location of the file/folder being created. +---@field uri string + +---Describes textual changes on a text document. A TextDocumentEdit describes all changes +---on a document version Si and after they are applied move the document to version Si+1. +---So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any +---kind of ordering. However the edits must be non overlapping. +---@class lsp.TextDocumentEdit +---The text document to change. +---@field textDocument lsp.OptionalVersionedTextDocumentIdentifier +---The edits to be applied. +--- +---@since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a +---client capability. +---@field edits lsp.TextEdit|lsp.AnnotatedTextEdit[] + +---Create file operation. +---@class lsp.CreateFile: lsp.ResourceOperation +---A create +---@field kind "create" +---The resource to create. +---@field uri lsp.DocumentUri +---Additional options +---@field options? lsp.CreateFileOptions + +---Rename file operation +---@class lsp.RenameFile: lsp.ResourceOperation +---A rename +---@field kind "rename" +---The old (existing) location. +---@field oldUri lsp.DocumentUri +---The new location. +---@field newUri lsp.DocumentUri +---Rename options. +---@field options? lsp.RenameFileOptions + +---Delete file operation +---@class lsp.DeleteFile: lsp.ResourceOperation +---A delete +---@field kind "delete" +---The file to delete. +---@field uri lsp.DocumentUri +---Delete options. +---@field options? lsp.DeleteFileOptions + +---Additional information that describes document changes. +--- +---@since 3.16.0 +---@class lsp.ChangeAnnotation +---A human-readable string describing the actual change. The string +---is rendered prominent in the user interface. +---@field label string +---A flag which indicates that user confirmation is needed +---before applying the change. +---@field needsConfirmation? boolean +---A human-readable string which is rendered less prominent in +---the user interface. +---@field description? string + +---A filter to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationFilter +---A Uri scheme like `file` or `untitled`. +---@field scheme? string +---The actual file operation pattern. +---@field pattern lsp.FileOperationPattern + +---Represents information on a file/folder rename. +--- +---@since 3.16.0 +---@class lsp.FileRename +---A file:// URI for the original location of the file/folder being renamed. +---@field oldUri string +---A file:// URI for the new location of the file/folder being renamed. +---@field newUri string + +---Represents information on a file/folder delete. +--- +---@since 3.16.0 +---@class lsp.FileDelete +---A file:// URI for the location of the file/folder being deleted. +---@field uri string + +---@class lsp.MonikerOptions + +---Type hierarchy options used during static registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyOptions + +---@since 3.17.0 +---@class lsp.InlineValueContext +---The stack frame (as a DAP Id) where the execution has stopped. +---@field frameId integer +---The document range where execution has stopped. +---Typically the end position of the range denotes the line where the inline values are shown. +---@field stoppedLocation lsp.Range + +---Provide inline value as text. +--- +---@since 3.17.0 +---@class lsp.InlineValueText +---The document range for which the inline value applies. +---@field range lsp.Range +---The text of the inline value. +---@field text string + +---Provide inline value through a variable lookup. +---If only a range is specified, the variable name will be extracted from the underlying document. +---An optional variable name can be used to override the extracted name. +--- +---@since 3.17.0 +---@class lsp.InlineValueVariableLookup +---The document range for which the inline value applies. +---The range is used to extract the variable name from the underlying document. +---@field range lsp.Range +---If specified the name of the variable to look up. +---@field variableName? string +---How to perform the lookup. +---@field caseSensitiveLookup boolean + +---Provide an inline value through an expression evaluation. +---If only a range is specified, the expression will be extracted from the underlying document. +---An optional expression can be used to override the extracted expression. +--- +---@since 3.17.0 +---@class lsp.InlineValueEvaluatableExpression +---The document range for which the inline value applies. +---The range is used to extract the evaluatable expression from the underlying document. +---@field range lsp.Range +---If specified the expression overrides the extracted expression. +---@field expression? string + +---Inline value options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueOptions + +---An inlay hint label part allows for interactive and composite labels +---of inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintLabelPart +---The value of this label part. +---@field value string +---The tooltip text when you hover over this label part. Depending on +---the client capability `inlayHint.resolveSupport` clients might resolve +---this property late using the resolve request. +---@field tooltip? string|lsp.MarkupContent +---An optional source code location that represents this +---label part. +--- +---The editor will use this location for the hover and for code navigation +---features: This part will become a clickable link that resolves to the +---definition of the symbol at the given location (not necessarily the +---location itself), it shows the hover that shows at the given location, +---and it shows a context menu with further code navigation commands. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field location? lsp.Location +---An optional command for this label part. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field command? lsp.Command + +---A `MarkupContent` literal represents a string value which content is interpreted base on its +---kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. +--- +---If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. +---See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---Here is an example how such a string can be constructed using JavaScript / TypeScript: +---```ts +---let markdown: MarkdownContent = { +--- kind: MarkupKind.Markdown, +--- value: [ +--- '# Header', +--- 'Some text', +--- '```typescript', +--- 'someCode();', +--- '```' +--- ].join('\n') +---}; +---``` +--- +---*Please Note* that clients might sanitize the return markdown. A client could decide to +---remove HTML from the markdown to avoid script execution. +---@class lsp.MarkupContent +---The type of the Markup +---@field kind lsp.MarkupKind +---The content itself +---@field value string + +---Inlay hint options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintOptions +---The server provides support to resolve additional +---information for an inlay hint item. +---@field resolveProvider? boolean + +---A full diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table + +---An unchanged diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table + +---A diagnostic report with a full set of problems. +--- +---@since 3.17.0 +---@class lsp.FullDocumentDiagnosticReport +---A full document diagnostic report. +---@field kind "full" +---An optional result id. If provided it will +---be sent on the next diagnostic request for the +---same document. +---@field resultId? string +---The actual items. +---@field items lsp.Diagnostic[] + +---A diagnostic report indicating that the last returned +---report is still accurate. +--- +---@since 3.17.0 +---@class lsp.UnchangedDocumentDiagnosticReport +---A document diagnostic report indicating +---no changes to the last result. A server can +---only return `unchanged` if result ids are +---provided. +---@field kind "unchanged" +---A result id which will be sent on the next +---diagnostic request for the same document. +---@field resultId string + +---Diagnostic options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticOptions +---An optional identifier under which the diagnostics are +---managed by the client. +---@field identifier? string +---Whether the language has inter file dependencies meaning that +---editing code in one file can result in a different diagnostic +---set in another file. Inter file dependencies are common for +---most programming languages and typically uncommon for linters. +---@field interFileDependencies boolean +---The server provides support for workspace diagnostics as well. +---@field workspaceDiagnostics boolean + +---A previous result id in a workspace pull request. +--- +---@since 3.17.0 +---@class lsp.PreviousResultId +---The URI for which the client knowns a +---result id. +---@field uri lsp.DocumentUri +---The value of the previous result id. +---@field value string + +---A notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocument +---The notebook document's uri. +---@field uri lsp.URI +---The type of the notebook. +---@field notebookType string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---Additional metadata stored with the notebook +---document. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---The cells of a notebook. +---@field cells lsp.NotebookCell[] + +---An item to transfer a text document from the client to the +---server. +---@class lsp.TextDocumentItem +---The text document's uri. +---@field uri lsp.DocumentUri +---The text document's language identifier. +---@field languageId string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---The content of the opened text document. +---@field text string + +---A versioned notebook document identifier. +--- +---@since 3.17.0 +---@class lsp.VersionedNotebookDocumentIdentifier +---The version number of this notebook document. +---@field version integer +---The notebook document's uri. +---@field uri lsp.URI + +---A change event for a notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentChangeEvent +---The changed meta data if any. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Changes to cells +---@field cells? anonym10 + +---A literal to identify a notebook document in the client. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentIdentifier +---The notebook document's uri. +---@field uri lsp.URI + +---Provides information about the context in which an inline completion was requested. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionContext +---Describes how the inline completion was triggered. +---@field triggerKind lsp.InlineCompletionTriggerKind +---Provides information about the currently selected item in the autocomplete widget if it is visible. +---@field selectedCompletionInfo? lsp.SelectedCompletionInfo + +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionOptions + +---General parameters to to register for an notification or to register a provider. +---@class lsp.Registration +---The id used to register the request. The id can be used to deregister +---the request again. +---@field id string +---The method / capability to register for. +---@field method string +---Options necessary for the registration. +---@field registerOptions? lsp.LSPAny + +---General parameters to unregister a request or notification. +---@class lsp.Unregistration +---The id used to unregister the request or notification. Usually an id +---provided during the register request. +---@field id string +---The method to unregister for. +---@field method string + +---The initialize parameters +---@class lsp._InitializeParams +---The process Id of the parent process that started +---the server. +--- +---Is `null` if the process has not been started by another process. +---If the parent process is not alive then the server should exit. +---@field processId integer|lsp.null +---Information about the client +--- +---@since 3.15.0 +---@field clientInfo? anonym11 +---The locale the client is currently showing the user interface +---in. This must not necessarily be the locale of the operating +---system. +--- +---Uses IETF language tags as the value's syntax +---(See https://en.wikipedia.org/wiki/IETF_language_tag) +--- +---@since 3.16.0 +---@field locale? string +---The rootPath of the workspace. Is null +---if no folder is open. +--- +---@deprecated in favour of rootUri. +---@field rootPath? string|lsp.null +---The rootUri of the workspace. Is null if no +---folder is open. If both `rootPath` and `rootUri` are set +---`rootUri` wins. +--- +---@deprecated in favour of workspaceFolders. +---@field rootUri lsp.DocumentUri|lsp.null +---The capabilities provided by the client (editor or tool) +---@field capabilities lsp.ClientCapabilities +---User provided initialization options. +---@field initializationOptions? lsp.LSPAny +---The initial trace setting. If omitted trace is disabled ('off'). +---@field trace? lsp.TraceValues + +---@class lsp.WorkspaceFoldersInitializeParams +---The workspace folders configured in the client when the server starts. +--- +---This property is only available if the client supports workspace folders. +---It can be `null` if the client supports workspace folders but none are +---configured. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFolder[]|lsp.null + +---Defines the capabilities provided by a language +---server. +---@class lsp.ServerCapabilities +---The position encoding the server picked from the encodings offered +---by the client via the client capability `general.positionEncodings`. +--- +---If the client didn't provide any position encodings the only valid +---value that a server can return is 'utf-16'. +--- +---If omitted it defaults to 'utf-16'. +--- +---@since 3.17.0 +---@field positionEncoding? lsp.PositionEncodingKind +---Defines how text documents are synced. Is either a detailed structure +---defining each notification or for backwards compatibility the +---TextDocumentSyncKind number. +---@field textDocumentSync? lsp.TextDocumentSyncOptions|lsp.TextDocumentSyncKind +---Defines how notebook documents are synced. +--- +---@since 3.17.0 +---@field notebookDocumentSync? lsp.NotebookDocumentSyncOptions|lsp.NotebookDocumentSyncRegistrationOptions +---The server provides completion support. +---@field completionProvider? lsp.CompletionOptions +---The server provides hover support. +---@field hoverProvider? boolean|lsp.HoverOptions +---The server provides signature help support. +---@field signatureHelpProvider? lsp.SignatureHelpOptions +---The server provides Goto Declaration support. +---@field declarationProvider? boolean|lsp.DeclarationOptions|lsp.DeclarationRegistrationOptions +---The server provides goto definition support. +---@field definitionProvider? boolean|lsp.DefinitionOptions +---The server provides Goto Type Definition support. +---@field typeDefinitionProvider? boolean|lsp.TypeDefinitionOptions|lsp.TypeDefinitionRegistrationOptions +---The server provides Goto Implementation support. +---@field implementationProvider? boolean|lsp.ImplementationOptions|lsp.ImplementationRegistrationOptions +---The server provides find references support. +---@field referencesProvider? boolean|lsp.ReferenceOptions +---The server provides document highlight support. +---@field documentHighlightProvider? boolean|lsp.DocumentHighlightOptions +---The server provides document symbol support. +---@field documentSymbolProvider? boolean|lsp.DocumentSymbolOptions +---The server provides code actions. CodeActionOptions may only be +---specified if the client states that it supports +---`codeActionLiteralSupport` in its initial `initialize` request. +---@field codeActionProvider? boolean|lsp.CodeActionOptions +---The server provides code lens. +---@field codeLensProvider? lsp.CodeLensOptions +---The server provides document link support. +---@field documentLinkProvider? lsp.DocumentLinkOptions +---The server provides color provider support. +---@field colorProvider? boolean|lsp.DocumentColorOptions|lsp.DocumentColorRegistrationOptions +---The server provides workspace symbol support. +---@field workspaceSymbolProvider? boolean|lsp.WorkspaceSymbolOptions +---The server provides document formatting. +---@field documentFormattingProvider? boolean|lsp.DocumentFormattingOptions +---The server provides document range formatting. +---@field documentRangeFormattingProvider? boolean|lsp.DocumentRangeFormattingOptions +---The server provides document formatting on typing. +---@field documentOnTypeFormattingProvider? lsp.DocumentOnTypeFormattingOptions +---The server provides rename support. RenameOptions may only be +---specified if the client states that it supports +---`prepareSupport` in its initial `initialize` request. +---@field renameProvider? boolean|lsp.RenameOptions +---The server provides folding provider support. +---@field foldingRangeProvider? boolean|lsp.FoldingRangeOptions|lsp.FoldingRangeRegistrationOptions +---The server provides selection range support. +---@field selectionRangeProvider? boolean|lsp.SelectionRangeOptions|lsp.SelectionRangeRegistrationOptions +---The server provides execute command support. +---@field executeCommandProvider? lsp.ExecuteCommandOptions +---The server provides call hierarchy support. +--- +---@since 3.16.0 +---@field callHierarchyProvider? boolean|lsp.CallHierarchyOptions|lsp.CallHierarchyRegistrationOptions +---The server provides linked editing range support. +--- +---@since 3.16.0 +---@field linkedEditingRangeProvider? boolean|lsp.LinkedEditingRangeOptions|lsp.LinkedEditingRangeRegistrationOptions +---The server provides semantic tokens support. +--- +---@since 3.16.0 +---@field semanticTokensProvider? lsp.SemanticTokensOptions|lsp.SemanticTokensRegistrationOptions +---The server provides moniker support. +--- +---@since 3.16.0 +---@field monikerProvider? boolean|lsp.MonikerOptions|lsp.MonikerRegistrationOptions +---The server provides type hierarchy support. +--- +---@since 3.17.0 +---@field typeHierarchyProvider? boolean|lsp.TypeHierarchyOptions|lsp.TypeHierarchyRegistrationOptions +---The server provides inline values. +--- +---@since 3.17.0 +---@field inlineValueProvider? boolean|lsp.InlineValueOptions|lsp.InlineValueRegistrationOptions +---The server provides inlay hints. +--- +---@since 3.17.0 +---@field inlayHintProvider? boolean|lsp.InlayHintOptions|lsp.InlayHintRegistrationOptions +---The server has support for pull model diagnostics. +--- +---@since 3.17.0 +---@field diagnosticProvider? lsp.DiagnosticOptions|lsp.DiagnosticRegistrationOptions +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@field inlineCompletionProvider? boolean|lsp.InlineCompletionOptions +---Workspace specific server capabilities. +---@field workspace? anonym12 +---Experimental server capabilities. +---@field experimental? lsp.LSPAny + +---A text document identifier to denote a specific version of a text document. +---@class lsp.VersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. +---@field version integer + +---Save options. +---@class lsp.SaveOptions +---The client is supposed to include the content on save. +---@field includeText? boolean + +---An event describing a file change. +---@class lsp.FileEvent +---The file's uri. +---@field uri lsp.DocumentUri +---The change type. +---@field type lsp.FileChangeType + +---@class lsp.FileSystemWatcher +---The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. +--- +---@since 3.17.0 support for relative patterns. +---@field globPattern lsp.GlobPattern +---The kind of events of interest. If omitted it defaults +---to WatchKind.Create | WatchKind.Change | WatchKind.Delete +---which is 7. +---@field kind? lsp.WatchKind + +---Represents a diagnostic, such as a compiler error or warning. Diagnostic objects +---are only valid in the scope of a resource. +---@class lsp.Diagnostic +---The range at which the message applies +---@field range lsp.Range +---The diagnostic's severity. Can be omitted. If omitted it is up to the +---client to interpret diagnostics as error, warning, info or hint. +---@field severity? lsp.DiagnosticSeverity +---The diagnostic's code, which usually appear in the user interface. +---@field code? integer|string +---An optional property to describe the error code. +---Requires the code field (above) to be present/not null. +--- +---@since 3.16.0 +---@field codeDescription? lsp.CodeDescription +---A human-readable string describing the source of this +---diagnostic, e.g. 'typescript' or 'super lint'. It usually +---appears in the user interface. +---@field source? string +---The diagnostic's message. It usually appears in the user interface +---@field message string +---Additional metadata about the diagnostic. +--- +---@since 3.15.0 +---@field tags? lsp.DiagnosticTag[] +---An array of related diagnostic information, e.g. when symbol-names within +---a scope collide all definitions can be marked via this property. +---@field relatedInformation? lsp.DiagnosticRelatedInformation[] +---A data entry field that is preserved between a `textDocument/publishDiagnostics` +---notification and `textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Contains additional information about the context in which a completion request is triggered. +---@class lsp.CompletionContext +---How the completion was triggered. +---@field triggerKind lsp.CompletionTriggerKind +---The trigger character (a single character) that has trigger code complete. +---Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` +---@field triggerCharacter? string + +---Additional details for a completion item label. +--- +---@since 3.17.0 +---@class lsp.CompletionItemLabelDetails +---An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, +---without any spacing. Should be used for function signatures and type annotations. +---@field detail? string +---An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used +---for fully qualified names and file paths. +---@field description? string + +---A special text edit to provide an insert and a replace operation. +--- +---@since 3.16.0 +---@class lsp.InsertReplaceEdit +---The string to be inserted. +---@field newText string +---The range if the insert is requested +---@field insert lsp.Range +---The range if the replace is requested. +---@field replace lsp.Range + +---Completion options. +---@class lsp.CompletionOptions +---Most tools trigger completion request automatically without explicitly requesting +---it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user +---starts to type an identifier. For example if the user types `c` in a JavaScript file +---code complete will automatically pop up present `console` besides others as a +---completion item. Characters that make up identifiers don't need to be listed here. +--- +---If code complete should automatically be trigger on characters not being valid inside +---an identifier (for example `.` in JavaScript) list them in `triggerCharacters`. +---@field triggerCharacters? string[] +---The list of all possible characters that commit a completion. This field can be used +---if clients don't support individual commit characters per completion item. See +---`ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` +--- +---If a server provides both `allCommitCharacters` and commit characters on an individual +---completion item the ones on the completion item win. +--- +---@since 3.2.0 +---@field allCommitCharacters? string[] +---The server provides support to resolve additional +---information for a completion item. +---@field resolveProvider? boolean +---The server supports the following `CompletionItem` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionItem? anonym13 + +---Hover options. +---@class lsp.HoverOptions + +---Additional information about the context in which a signature help request was triggered. +--- +---@since 3.15.0 +---@class lsp.SignatureHelpContext +---Action that caused signature help to be triggered. +---@field triggerKind lsp.SignatureHelpTriggerKind +---Character that caused signature help to be triggered. +--- +---This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` +---@field triggerCharacter? string +---`true` if signature help was already showing when it was triggered. +--- +---Retriggers occurs when the signature help is already active and can be caused by actions such as +---typing a trigger character, a cursor move, or document content changes. +---@field isRetrigger boolean +---The currently active `SignatureHelp`. +--- +---The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on +---the user navigating through available signatures. +---@field activeSignatureHelp? lsp.SignatureHelp + +---Represents the signature of something callable. A signature +---can have a label, like a function-name, a doc-comment, and +---a set of parameters. +---@class lsp.SignatureInformation +---The label of this signature. Will be shown in +---the UI. +---@field label string +---The human-readable doc-comment of this signature. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent +---The parameters of this signature. +---@field parameters? lsp.ParameterInformation[] +---The index of the active parameter. +--- +---If provided, this is used in place of `SignatureHelp.activeParameter`. +--- +---@since 3.16.0 +---@field activeParameter? uinteger + +---Server Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpOptions +---List of characters that trigger signature help automatically. +---@field triggerCharacters? string[] +---List of characters that re-trigger signature help. +--- +---These trigger characters are only active when signature help is already showing. All trigger characters +---are also counted as re-trigger characters. +--- +---@since 3.15.0 +---@field retriggerCharacters? string[] + +---Server Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionOptions + +---Value-object that contains additional information when +---requesting references. +---@class lsp.ReferenceContext +---Include the declaration of the current symbol. +---@field includeDeclaration boolean + +---Reference options. +---@class lsp.ReferenceOptions + +---Provider options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightOptions + +---A base for all symbol information. +---@class lsp.BaseSymbolInformation +---The name of this symbol. +---@field name string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---The name of the symbol containing this symbol. This information is for +---user interface purposes (e.g. to render a qualifier in the user interface +---if necessary). It can't be used to re-infer a hierarchy for the document +---symbols. +---@field containerName? string + +---Provider options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolOptions +---A human-readable string that is shown when multiple outlines trees +---are shown for the same document. +--- +---@since 3.16.0 +---@field label? string + +---Contains additional diagnostic information about the context in which +---a {@link CodeActionProvider.provideCodeActions code action} is run. +---@class lsp.CodeActionContext +---An array of diagnostics known on the client side overlapping the range provided to the +---`textDocument/codeAction` request. They are provided so that the server knows which +---errors are currently presented to the user for the given range. There is no guarantee +---that these accurately reflect the error state of the resource. The primary parameter +---to compute code actions is the provided range. +---@field diagnostics lsp.Diagnostic[] +---Requested kind of actions to return. +--- +---Actions not of this kind are filtered out by the client before being shown. So servers +---can omit computing them. +---@field only? lsp.CodeActionKind[] +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@field triggerKind? lsp.CodeActionTriggerKind + +---Provider options for a {@link CodeActionRequest}. +---@class lsp.CodeActionOptions +---CodeActionKinds that this server may return. +--- +---The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server +---may list out every specific kind they provide. +---@field codeActionKinds? lsp.CodeActionKind[] +---The server provides support to resolve additional +---information for a code action. +--- +---@since 3.16.0 +---@field resolveProvider? boolean + +---Server capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolOptions +---The server provides support to resolve additional +---information for a workspace symbol. +--- +---@since 3.17.0 +---@field resolveProvider? boolean + +---Code Lens provider options of a {@link CodeLensRequest}. +---@class lsp.CodeLensOptions +---Code lens has a resolve provider as well. +---@field resolveProvider? boolean + +---Provider options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkOptions +---Document links have a resolve provider as well. +---@field resolveProvider? boolean + +---Value-object describing what options formatting should use. +---@class lsp.FormattingOptions +---Size of a tab in spaces. +---@field tabSize uinteger +---Prefer spaces over tabs. +---@field insertSpaces boolean +---Trim trailing whitespace on a line. +--- +---@since 3.15.0 +---@field trimTrailingWhitespace? boolean +---Insert a newline character at the end of the file if one does not exist. +--- +---@since 3.15.0 +---@field insertFinalNewline? boolean +---Trim all newlines after the final newline at the end of the file. +--- +---@since 3.15.0 +---@field trimFinalNewlines? boolean + +---Provider options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingOptions + +---Provider options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingOptions +---Whether the server supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean + +---Provider options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingOptions +---A character on which formatting should be triggered, like `{`. +---@field firstTriggerCharacter string +---More trigger characters. +---@field moreTriggerCharacter? string[] + +---Provider options for a {@link RenameRequest}. +---@class lsp.RenameOptions +---Renames should be checked and tested before being executed. +--- +---@since version 3.12.0 +---@field prepareProvider? boolean + +---The server capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandOptions +---The commands to be executed on the server +---@field commands string[] + +---@since 3.16.0 +---@class lsp.SemanticTokensLegend +---The token types a server uses. +---@field tokenTypes string[] +---The token modifiers a server uses. +---@field tokenModifiers string[] + +---A text document identifier to optionally denote a specific version of a text document. +---@class lsp.OptionalVersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. If a versioned text document identifier +---is sent from the server to the client and the file is not open in the editor +---(the server has not received an open notification before) the server can send +---`null` to indicate that the version is unknown and the content on disk is the +---truth (as specified with document content ownership). +---@field version integer|lsp.null + +---A special text edit with an additional change annotation. +--- +---@since 3.16.0. +---@class lsp.AnnotatedTextEdit: lsp.TextEdit +---The actual identifier of the change annotation +---@field annotationId lsp.ChangeAnnotationIdentifier + +---A generic resource operation. +---@class lsp.ResourceOperation +---The resource operation kind. +---@field kind string +---An optional annotation identifier describing the operation. +--- +---@since 3.16.0 +---@field annotationId? lsp.ChangeAnnotationIdentifier + +---Options to create a file. +---@class lsp.CreateFileOptions +---Overwrite existing file. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignore if exists. +---@field ignoreIfExists? boolean + +---Rename file options +---@class lsp.RenameFileOptions +---Overwrite target if existing. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignores if target exists. +---@field ignoreIfExists? boolean + +---Delete file options +---@class lsp.DeleteFileOptions +---Delete the content recursively if a folder is denoted. +---@field recursive? boolean +---Ignore the operation if the file doesn't exist. +---@field ignoreIfNotExists? boolean + +---A pattern to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationPattern +---The glob pattern to match. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +---@field glob string +---Whether to match files or folders with this pattern. +--- +---Matches both if undefined. +---@field matches? lsp.FileOperationPatternKind +---Additional options used during matching. +---@field options? lsp.FileOperationPatternOptions + +---A full document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---An unchanged document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---A notebook cell. +--- +---A cell's document URI must be unique across ALL notebook +---cells and can therefore be used to uniquely identify a +---notebook cell or the cell's text document. +--- +---@since 3.17.0 +---@class lsp.NotebookCell +---The cell's kind +---@field kind lsp.NotebookCellKind +---The URI of the cell's text document +---content. +---@field document lsp.DocumentUri +---Additional metadata stored with the cell. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Additional execution summary information +---if supported by the client. +---@field executionSummary? lsp.ExecutionSummary + +---A change describing how to move a `NotebookCell` +---array from state S to S'. +--- +---@since 3.17.0 +---@class lsp.NotebookCellArrayChange +---The start oftest of the cell that changed. +---@field start uinteger +---The deleted cells +---@field deleteCount uinteger +---The new cells, if any +---@field cells? lsp.NotebookCell[] + +---Describes the currently selected completion item. +--- +---@since 3.18.0 +---@class lsp.SelectedCompletionInfo +---The range that will be replaced if this completion item is accepted. +---@field range lsp.Range +---The text the range will be replaced with if this completion is accepted. +---@field text string + +---Defines the capabilities provided by the client. +---@class lsp.ClientCapabilities +---Workspace specific client capabilities. +---@field workspace? lsp.WorkspaceClientCapabilities +---Text document specific client capabilities. +---@field textDocument? lsp.TextDocumentClientCapabilities +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@field notebookDocument? lsp.NotebookDocumentClientCapabilities +---Window specific client capabilities. +---@field window? lsp.WindowClientCapabilities +---General client capabilities. +--- +---@since 3.16.0 +---@field general? lsp.GeneralClientCapabilities +---Experimental client capabilities. +---@field experimental? lsp.LSPAny + +---@class lsp.TextDocumentSyncOptions +---Open and close notifications are sent to the server. If omitted open close notification should not +---be sent. +---@field openClose? boolean +---Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full +---and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. +---@field change? lsp.TextDocumentSyncKind +---If present will save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field willSave? boolean +---If present will save wait until requests are sent to the server. If omitted the request should not be +---sent. +---@field willSaveWaitUntil? boolean +---If present save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field save? boolean|lsp.SaveOptions + +---Options specific to a notebook plus its cells +---to be synced to the server. +--- +---If a selector provides a notebook document +---filter but no cell selector all cells of a +---matching notebook document will be synced. +--- +---If a selector provides no notebook document +---filter but only a cell selector all notebook +---document that contain at least one matching +---cell will be synced. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncOptions +---The notebooks to be synced +---@field notebookSelector anonym15|anonym17[] +---Whether save notification should be forwarded to +---the server. Will only be honored if mode === `notebook`. +---@field save? boolean + +---Registration options specific to a notebook. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncRegistrationOptions: lsp.NotebookDocumentSyncOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkspaceFoldersServerCapabilities +---The server has support for workspace folders +---@field supported? boolean +---Whether the server wants to receive workspace folder +---change notifications. +--- +---If a string is provided the string is treated as an ID +---under which the notification is registered on the client +---side. The ID can be used to unregister for these events +---using the `client/unregisterCapability` request. +---@field changeNotifications? string|boolean + +---Options for notifications/requests for user operations on files. +--- +---@since 3.16.0 +---@class lsp.FileOperationOptions +---The server is interested in receiving didCreateFiles notifications. +---@field didCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willCreateFiles requests. +---@field willCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didRenameFiles notifications. +---@field didRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willRenameFiles requests. +---@field willRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didDeleteFiles file notifications. +---@field didDelete? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willDeleteFiles file requests. +---@field willDelete? lsp.FileOperationRegistrationOptions + +---Structure to capture a description for an error code. +--- +---@since 3.16.0 +---@class lsp.CodeDescription +---An URI to open with more information about the diagnostic error. +---@field href lsp.URI + +---Represents a related message and source code location for a diagnostic. This should be +---used to point to code locations that cause or related to a diagnostics, e.g when duplicating +---a symbol in a scope. +---@class lsp.DiagnosticRelatedInformation +---The location of this related diagnostic information. +---@field location lsp.Location +---The message of this related diagnostic information. +---@field message string + +---Represents a parameter of a callable-signature. A parameter can +---have a label and a doc-comment. +---@class lsp.ParameterInformation +---The label of this parameter information. +--- +---Either a string or an inclusive start and exclusive end offsets within its containing +---signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 +---string representation as `Position` and `Range` does. +--- +---*Note*: a label of type string should be a substring of its containing signature label. +---Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. +---@field label string|{ [1]: uinteger, [2]: uinteger } +---The human-readable doc-comment of this parameter. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent + +---A notebook cell text document filter denotes a cell text +---document by different properties. +--- +---@since 3.17.0 +---@class lsp.NotebookCellTextDocumentFilter +---A filter that matches against the notebook +---containing the notebook cell. If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---A language id like `python`. +--- +---Will be matched against the language id of the +---notebook cell document. '*' matches every language. +---@field language? string + +---Matching options for the file operation pattern. +--- +---@since 3.16.0 +---@class lsp.FileOperationPatternOptions +---The pattern should be matched ignoring casing. +---@field ignoreCase? boolean + +---@class lsp.ExecutionSummary +---A strict monotonically increasing value +---indicating the execution order of a cell +---inside a notebook. +---@field executionOrder uinteger +---Whether the execution was successful or +---not if known by the client. +---@field success? boolean + +---Workspace specific client capabilities. +---@class lsp.WorkspaceClientCapabilities +---The client supports applying batch edits +---to the workspace by supporting the request +---'workspace/applyEdit' +---@field applyEdit? boolean +---Capabilities specific to `WorkspaceEdit`s. +---@field workspaceEdit? lsp.WorkspaceEditClientCapabilities +---Capabilities specific to the `workspace/didChangeConfiguration` notification. +---@field didChangeConfiguration? lsp.DidChangeConfigurationClientCapabilities +---Capabilities specific to the `workspace/didChangeWatchedFiles` notification. +---@field didChangeWatchedFiles? lsp.DidChangeWatchedFilesClientCapabilities +---Capabilities specific to the `workspace/symbol` request. +---@field symbol? lsp.WorkspaceSymbolClientCapabilities +---Capabilities specific to the `workspace/executeCommand` request. +---@field executeCommand? lsp.ExecuteCommandClientCapabilities +---The client has support for workspace folders. +--- +---@since 3.6.0 +---@field workspaceFolders? boolean +---The client supports `workspace/configuration` requests. +--- +---@since 3.6.0 +---@field configuration? boolean +---Capabilities specific to the semantic token requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field semanticTokens? lsp.SemanticTokensWorkspaceClientCapabilities +---Capabilities specific to the code lens requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field codeLens? lsp.CodeLensWorkspaceClientCapabilities +---The client has support for file notifications/requests for user operations on files. +--- +---Since 3.16.0 +---@field fileOperations? lsp.FileOperationClientCapabilities +---Capabilities specific to the inline values requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlineValue? lsp.InlineValueWorkspaceClientCapabilities +---Capabilities specific to the inlay hint requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlayHint? lsp.InlayHintWorkspaceClientCapabilities +---Capabilities specific to the diagnostic requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field diagnostics? lsp.DiagnosticWorkspaceClientCapabilities + +---Text document specific client capabilities. +---@class lsp.TextDocumentClientCapabilities +---Defines which synchronization capabilities the client supports. +---@field synchronization? lsp.TextDocumentSyncClientCapabilities +---Capabilities specific to the `textDocument/completion` request. +---@field completion? lsp.CompletionClientCapabilities +---Capabilities specific to the `textDocument/hover` request. +---@field hover? lsp.HoverClientCapabilities +---Capabilities specific to the `textDocument/signatureHelp` request. +---@field signatureHelp? lsp.SignatureHelpClientCapabilities +---Capabilities specific to the `textDocument/declaration` request. +--- +---@since 3.14.0 +---@field declaration? lsp.DeclarationClientCapabilities +---Capabilities specific to the `textDocument/definition` request. +---@field definition? lsp.DefinitionClientCapabilities +---Capabilities specific to the `textDocument/typeDefinition` request. +--- +---@since 3.6.0 +---@field typeDefinition? lsp.TypeDefinitionClientCapabilities +---Capabilities specific to the `textDocument/implementation` request. +--- +---@since 3.6.0 +---@field implementation? lsp.ImplementationClientCapabilities +---Capabilities specific to the `textDocument/references` request. +---@field references? lsp.ReferenceClientCapabilities +---Capabilities specific to the `textDocument/documentHighlight` request. +---@field documentHighlight? lsp.DocumentHighlightClientCapabilities +---Capabilities specific to the `textDocument/documentSymbol` request. +---@field documentSymbol? lsp.DocumentSymbolClientCapabilities +---Capabilities specific to the `textDocument/codeAction` request. +---@field codeAction? lsp.CodeActionClientCapabilities +---Capabilities specific to the `textDocument/codeLens` request. +---@field codeLens? lsp.CodeLensClientCapabilities +---Capabilities specific to the `textDocument/documentLink` request. +---@field documentLink? lsp.DocumentLinkClientCapabilities +---Capabilities specific to the `textDocument/documentColor` and the +---`textDocument/colorPresentation` request. +--- +---@since 3.6.0 +---@field colorProvider? lsp.DocumentColorClientCapabilities +---Capabilities specific to the `textDocument/formatting` request. +---@field formatting? lsp.DocumentFormattingClientCapabilities +---Capabilities specific to the `textDocument/rangeFormatting` request. +---@field rangeFormatting? lsp.DocumentRangeFormattingClientCapabilities +---Capabilities specific to the `textDocument/onTypeFormatting` request. +---@field onTypeFormatting? lsp.DocumentOnTypeFormattingClientCapabilities +---Capabilities specific to the `textDocument/rename` request. +---@field rename? lsp.RenameClientCapabilities +---Capabilities specific to the `textDocument/foldingRange` request. +--- +---@since 3.10.0 +---@field foldingRange? lsp.FoldingRangeClientCapabilities +---Capabilities specific to the `textDocument/selectionRange` request. +--- +---@since 3.15.0 +---@field selectionRange? lsp.SelectionRangeClientCapabilities +---Capabilities specific to the `textDocument/publishDiagnostics` notification. +---@field publishDiagnostics? lsp.PublishDiagnosticsClientCapabilities +---Capabilities specific to the various call hierarchy requests. +--- +---@since 3.16.0 +---@field callHierarchy? lsp.CallHierarchyClientCapabilities +---Capabilities specific to the various semantic token request. +--- +---@since 3.16.0 +---@field semanticTokens? lsp.SemanticTokensClientCapabilities +---Capabilities specific to the `textDocument/linkedEditingRange` request. +--- +---@since 3.16.0 +---@field linkedEditingRange? lsp.LinkedEditingRangeClientCapabilities +---Client capabilities specific to the `textDocument/moniker` request. +--- +---@since 3.16.0 +---@field moniker? lsp.MonikerClientCapabilities +---Capabilities specific to the various type hierarchy requests. +--- +---@since 3.17.0 +---@field typeHierarchy? lsp.TypeHierarchyClientCapabilities +---Capabilities specific to the `textDocument/inlineValue` request. +--- +---@since 3.17.0 +---@field inlineValue? lsp.InlineValueClientCapabilities +---Capabilities specific to the `textDocument/inlayHint` request. +--- +---@since 3.17.0 +---@field inlayHint? lsp.InlayHintClientCapabilities +---Capabilities specific to the diagnostic pull model. +--- +---@since 3.17.0 +---@field diagnostic? lsp.DiagnosticClientCapabilities +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@field inlineCompletion? lsp.InlineCompletionClientCapabilities + +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentClientCapabilities +---Capabilities specific to notebook document synchronization +--- +---@since 3.17.0 +---@field synchronization lsp.NotebookDocumentSyncClientCapabilities + +---@class lsp.WindowClientCapabilities +---It indicates whether the client supports server initiated +---progress using the `window/workDoneProgress/create` request. +--- +---The capability also controls Whether client supports handling +---of progress notifications. If set servers are allowed to report a +---`workDoneProgress` property in the request specific server +---capabilities. +--- +---@since 3.15.0 +---@field workDoneProgress? boolean +---Capabilities specific to the showMessage request. +--- +---@since 3.16.0 +---@field showMessage? lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the showDocument request. +--- +---@since 3.16.0 +---@field showDocument? lsp.ShowDocumentClientCapabilities + +---General client capabilities. +--- +---@since 3.16.0 +---@class lsp.GeneralClientCapabilities +---Client capability that signals how the client +---handles stale requests (e.g. a request +---for which the client will not process the response +---anymore since the information is outdated). +--- +---@since 3.17.0 +---@field staleRequestSupport? anonym18 +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@field regularExpressions? lsp.RegularExpressionsClientCapabilities +---Client capabilities specific to the client's markdown parser. +--- +---@since 3.16.0 +---@field markdown? lsp.MarkdownClientCapabilities +---The position encodings supported by the client. Client and server +---have to agree on the same position encoding to ensure that offsets +---(e.g. character position in a line) are interpreted the same on both +---sides. +--- +---To keep the protocol backwards compatible the following applies: if +---the value 'utf-16' is missing from the array of position encodings +---servers can assume that the client supports UTF-16. UTF-16 is +---therefore a mandatory encoding. +--- +---If omitted it defaults to ['utf-16']. +--- +---Implementation considerations: since the conversion from one encoding +---into another requires the content of the file / line the conversion +---is best done where the file is read which is usually on the server +---side. +--- +---@since 3.17.0 +---@field positionEncodings? lsp.PositionEncodingKind[] + +---A relative pattern is a helper to construct glob patterns that are matched +---relatively to a base URI. The common value for a `baseUri` is a workspace +---folder root, but it can be another absolute URI as well. +--- +---@since 3.17.0 +---@class lsp.RelativePattern +---A workspace folder or a base URI to which this pattern will be matched +---against relatively. +---@field baseUri lsp.WorkspaceFolder|lsp.URI +---The actual glob pattern; +---@field pattern lsp.Pattern + +---@class lsp.WorkspaceEditClientCapabilities +---The client supports versioned document changes in `WorkspaceEdit`s +---@field documentChanges? boolean +---The resource operations the client supports. Clients should at least +---support 'create', 'rename' and 'delete' files and folders. +--- +---@since 3.13.0 +---@field resourceOperations? lsp.ResourceOperationKind[] +---The failure handling strategy of a client if applying the workspace edit +---fails. +--- +---@since 3.13.0 +---@field failureHandling? lsp.FailureHandlingKind +---Whether the client normalizes line endings to the client specific +---setting. +---If set to `true` the client will normalize line ending characters +---in a workspace edit to the client-specified new line +---character. +--- +---@since 3.16.0 +---@field normalizesLineEndings? boolean +---Whether the client in general supports change annotations on text edits, +---create file, rename file and delete file changes. +--- +---@since 3.16.0 +---@field changeAnnotationSupport? anonym19 + +---@class lsp.DidChangeConfigurationClientCapabilities +---Did change configuration notification supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.DidChangeWatchedFilesClientCapabilities +---Did change watched files notification supports dynamic registration. Please note +---that the current protocol doesn't support static configuration for file changes +---from the server side. +---@field dynamicRegistration? boolean +---Whether the client has support for {@link RelativePattern relative pattern} +---or not. +--- +---@since 3.17.0 +---@field relativePatternSupport? boolean + +---Client capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolClientCapabilities +---Symbol request supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. +---@field symbolKind? anonym20 +---The client supports tags on `SymbolInformation`. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym21 +---The client support partial workspace symbols. The client will send the +---request `workspaceSymbol/resolve` to the server to resolve additional +---properties. +--- +---@since 3.17.0 +---@field resolveSupport? anonym22 + +---The client capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandClientCapabilities +---Execute command supports dynamic registration. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---semantic tokens currently shown. It should be used with absolute care +---and is useful for situation where a server for example detects a project +---wide change that requires such a calculation. +---@field refreshSupport? boolean + +---@since 3.16.0 +---@class lsp.CodeLensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---code lenses currently shown. It should be used with absolute care and is +---useful for situation where a server for example detect a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Capabilities relating to events from file operations by the user in the client. +--- +---These events do not come from the file system, they come from user operations +---like renaming a file in the UI. +--- +---@since 3.16.0 +---@class lsp.FileOperationClientCapabilities +---Whether the client supports dynamic registration for file requests/notifications. +---@field dynamicRegistration? boolean +---The client has support for sending didCreateFiles notifications. +---@field didCreate? boolean +---The client has support for sending willCreateFiles requests. +---@field willCreate? boolean +---The client has support for sending didRenameFiles notifications. +---@field didRename? boolean +---The client has support for sending willRenameFiles requests. +---@field willRename? boolean +---The client has support for sending didDeleteFiles notifications. +---@field didDelete? boolean +---The client has support for sending willDeleteFiles requests. +---@field willDelete? boolean + +---Client workspace capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inline values currently shown. It should be used with absolute care and is +---useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Client workspace capabilities specific to inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inlay hints currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Workspace client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---pulled diagnostics currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---@class lsp.TextDocumentSyncClientCapabilities +---Whether text document synchronization supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports sending will save notifications. +---@field willSave? boolean +---The client supports sending a will save request and +---waits for a response providing text edits which will +---be applied to the document before it is saved. +---@field willSaveWaitUntil? boolean +---The client supports did save notifications. +---@field didSave? boolean + +---Completion client capabilities +---@class lsp.CompletionClientCapabilities +---Whether completion supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `CompletionItem` specific +---capabilities. +---@field completionItem? anonym26 +---@field completionItemKind? anonym27 +---Defines how the client handles whitespace and indentation +---when accepting a completion item that uses multi line +---text in either `insertText` or `textEdit`. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---The client supports to send additional context information for a +---`textDocument/completion` request. +---@field contextSupport? boolean +---The client supports the following `CompletionList` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionList? anonym28 + +---@class lsp.HoverClientCapabilities +---Whether hover supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports the following content formats for the content +---property. The order describes the preferred format of the client. +---@field contentFormat? lsp.MarkupKind[] + +---Client Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpClientCapabilities +---Whether signature help supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `SignatureInformation` +---specific properties. +---@field signatureInformation? anonym30 +---The client supports to send additional context information for a +---`textDocument/signatureHelp` request. A client that opts into +---contextSupport will also support the `retriggerCharacters` on +---`SignatureHelpOptions`. +--- +---@since 3.15.0 +---@field contextSupport? boolean + +---@since 3.14.0 +---@class lsp.DeclarationClientCapabilities +---Whether declaration supports dynamic registration. If this is set to `true` +---the client supports the new `DeclarationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of declaration links. +---@field linkSupport? boolean + +---Client Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionClientCapabilities +---Whether definition supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Since 3.6.0 +---@class lsp.TypeDefinitionClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `TypeDefinitionRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---Since 3.14.0 +---@field linkSupport? boolean + +---@since 3.6.0 +---@class lsp.ImplementationClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `ImplementationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Client Capabilities for a {@link ReferencesRequest}. +---@class lsp.ReferenceClientCapabilities +---Whether references supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightClientCapabilities +---Whether document highlight supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolClientCapabilities +---Whether document symbol supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the +---`textDocument/documentSymbol` request. +---@field symbolKind? anonym31 +---The client supports hierarchical document symbols. +---@field hierarchicalDocumentSymbolSupport? boolean +---The client supports tags on `SymbolInformation`. Tags are supported on +---`DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym32 +---The client supports an additional label presented in the UI when +---registering a document symbol provider. +--- +---@since 3.16.0 +---@field labelSupport? boolean + +---The Client Capabilities of a {@link CodeActionRequest}. +---@class lsp.CodeActionClientCapabilities +---Whether code action supports dynamic registration. +---@field dynamicRegistration? boolean +---The client support code action literals of type `CodeAction` as a valid +---response of the `textDocument/codeAction` request. If the property is not +---set the request can only return `Command` literals. +--- +---@since 3.8.0 +---@field codeActionLiteralSupport? anonym34 +---Whether code action supports the `isPreferred` property. +--- +---@since 3.15.0 +---@field isPreferredSupport? boolean +---Whether code action supports the `disabled` property. +--- +---@since 3.16.0 +---@field disabledSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/codeAction` and a +---`codeAction/resolve` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean +---Whether the client supports resolving additional code action +---properties via a separate `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field resolveSupport? anonym35 +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---`CodeAction#edit` property by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---The client capabilities of a {@link CodeLensRequest}. +---@class lsp.CodeLensClientCapabilities +---Whether code lens supports dynamic registration. +---@field dynamicRegistration? boolean + +---The client capabilities of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkClientCapabilities +---Whether document link supports dynamic registration. +---@field dynamicRegistration? boolean +---Whether the client supports the `tooltip` property on `DocumentLink`. +--- +---@since 3.15.0 +---@field tooltipSupport? boolean + +---@class lsp.DocumentColorClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `DocumentColorRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingClientCapabilities +---Whether formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingClientCapabilities +---Whether range formatting supports dynamic registration. +---@field dynamicRegistration? boolean +---Whether the client supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean + +---Client capabilities of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingClientCapabilities +---Whether on type formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.RenameClientCapabilities +---Whether rename supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports testing for validity of rename operations +---before execution. +--- +---@since 3.12.0 +---@field prepareSupport? boolean +---Client supports the default behavior result. +--- +---The value indicates the default behavior used by the +---client. +--- +---@since 3.16.0 +---@field prepareSupportDefaultBehavior? lsp.PrepareSupportDefaultBehavior +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---rename request's workspace edit by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---@class lsp.FoldingRangeClientCapabilities +---Whether implementation supports dynamic registration for folding range +---providers. If this is set to `true` the client supports the new +---`FoldingRangeRegistrationOptions` return value for the corresponding +---server capability as well. +---@field dynamicRegistration? boolean +---The maximum number of folding ranges that the client prefers to receive +---per document. The value serves as a hint, servers are free to follow the +---limit. +---@field rangeLimit? uinteger +---If set, the client signals that it only supports folding complete lines. +---If set, client will ignore specified `startCharacter` and `endCharacter` +---properties in a FoldingRange. +---@field lineFoldingOnly? boolean +---Specific options for the folding range kind. +--- +---@since 3.17.0 +---@field foldingRangeKind? anonym36 +---Specific options for the folding range. +--- +---@since 3.17.0 +---@field foldingRange? anonym37 + +---@class lsp.SelectionRangeClientCapabilities +---Whether implementation supports dynamic registration for selection range providers. If this is set to `true` +---the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server +---capability as well. +---@field dynamicRegistration? boolean + +---The publish diagnostic client capabilities. +---@class lsp.PublishDiagnosticsClientCapabilities +---Whether the clients accepts diagnostics with related information. +---@field relatedInformation? boolean +---Client supports the tag property to provide meta data about a diagnostic. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.15.0 +---@field tagSupport? anonym38 +---Whether the client interprets the version property of the +---`textDocument/publishDiagnostics` notification's parameter. +--- +---@since 3.15.0 +---@field versionSupport? boolean +---Client supports a codeDescription property +--- +---@since 3.16.0 +---@field codeDescriptionSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/publishDiagnostics` and +---`textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean + +---@since 3.16.0 +---@class lsp.CallHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Which requests the client supports and might send to the server +---depending on the server's capability. Please note that clients might not +---show semantic tokens or degrade some of the user experience if a range +---or full request is advertised by the client but not provided by the +---server. If for example the client capability `requests.full` and +---`request.range` are both set to true but the server only provides a +---range provider the client might not render a minimap correctly or might +---even decide to not show any semantic tokens at all. +---@field requests anonym41 +---The token types that the client supports. +---@field tokenTypes string[] +---The token modifiers that the client supports. +---@field tokenModifiers string[] +---The token formats the clients supports. +---@field formats lsp.TokenFormat[] +---Whether the client supports tokens that can overlap each other. +---@field overlappingTokenSupport? boolean +---Whether the client supports tokens that can span multiple lines. +---@field multilineTokenSupport? boolean +---Whether the client allows the server to actively cancel a +---semantic token request, e.g. supports returning +---LSPErrorCodes.ServerCancelled. If a server does the client +---needs to retrigger the request. +--- +---@since 3.17.0 +---@field serverCancelSupport? boolean +---Whether the client uses semantic tokens to augment existing +---syntax tokens. If set to `true` client side created syntax +---tokens and semantic tokens are both used for colorization. If +---set to `false` the client only uses the returned semantic tokens +---for colorization. +--- +---If the value is `undefined` then the client behavior is not +---specified. +--- +---@since 3.17.0 +---@field augmentsSyntaxTokens? boolean + +---Client capabilities for the linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRangeClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to the moniker request. +--- +---@since 3.16.0 +---@class lsp.MonikerClientCapabilities +---Whether moniker supports dynamic registration. If this is set to `true` +---the client supports the new `MonikerRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.17.0 +---@class lsp.TypeHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueClientCapabilities +---Whether implementation supports dynamic registration for inline value providers. +---@field dynamicRegistration? boolean + +---Inlay hint client capabilities. +--- +---@since 3.17.0 +---@class lsp.InlayHintClientCapabilities +---Whether inlay hints support dynamic registration. +---@field dynamicRegistration? boolean +---Indicates which properties a client can resolve lazily on an inlay +---hint. +---@field resolveSupport? anonym42 + +---Client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Whether the clients supports related documents for document diagnostic pulls. +---@field relatedDocumentSupport? boolean + +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionClientCapabilities +---Whether implementation supports dynamic registration for inline completion providers. +---@field dynamicRegistration? boolean + +---Notebook specific client capabilities. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncClientCapabilities +---Whether implementation supports dynamic registration. If this is +---set to `true` the client supports the new +---`(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports sending execution summary data per cell. +---@field executionSummarySupport? boolean + +---Show message request client capabilities +---@class lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the `MessageActionItem` type. +---@field messageActionItem? anonym43 + +---Client capabilities for the showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentClientCapabilities +---The client has support for the showDocument +---request. +---@field support boolean + +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@class lsp.RegularExpressionsClientCapabilities +---The engine's name. +---@field engine string +---The engine's version. +---@field version? string + +---Client capabilities specific to the used markdown parser. +--- +---@since 3.16.0 +---@class lsp.MarkdownClientCapabilities +---The name of the parser. +---@field parser string +---The version of the parser. +---@field version? string +---A list of HTML tags that the client allows / supports in +---Markdown. +--- +---@since 3.17.0 +---@field allowedTags? string[] + +---A set of predefined token types. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenTypes +---| "namespace" # namespace +---| "type" # type +---| "class" # class +---| "enum" # enum +---| "interface" # interface +---| "struct" # struct +---| "typeParameter" # typeParameter +---| "parameter" # parameter +---| "variable" # variable +---| "property" # property +---| "enumMember" # enumMember +---| "event" # event +---| "function" # function +---| "method" # method +---| "macro" # macro +---| "keyword" # keyword +---| "modifier" # modifier +---| "comment" # comment +---| "string" # string +---| "number" # number +---| "regexp" # regexp +---| "operator" # operator +---| "decorator" # decorator + +---A set of predefined token modifiers. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenModifiers +---| "declaration" # declaration +---| "definition" # definition +---| "readonly" # readonly +---| "static" # static +---| "deprecated" # deprecated +---| "abstract" # abstract +---| "async" # async +---| "modification" # modification +---| "documentation" # documentation +---| "defaultLibrary" # defaultLibrary + +---The document diagnostic report kinds. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReportKind +---| "full" # Full +---| "unchanged" # Unchanged + +---Predefined error codes. +---@alias lsp.ErrorCodes +---| -32700 # ParseError +---| -32600 # InvalidRequest +---| -32601 # MethodNotFound +---| -32602 # InvalidParams +---| -32603 # InternalError +---| -32002 # ServerNotInitialized +---| -32001 # UnknownErrorCode + +---@alias lsp.LSPErrorCodes +---| -32803 # RequestFailed +---| -32802 # ServerCancelled +---| -32801 # ContentModified +---| -32800 # RequestCancelled + +---A set of predefined range kinds. +---@alias lsp.FoldingRangeKind +---| "comment" # Comment +---| "imports" # Imports +---| "region" # Region + +---A symbol kind. +---@alias lsp.SymbolKind +---| 1 # File +---| 2 # Module +---| 3 # Namespace +---| 4 # Package +---| 5 # Class +---| 6 # Method +---| 7 # Property +---| 8 # Field +---| 9 # Constructor +---| 10 # Enum +---| 11 # Interface +---| 12 # Function +---| 13 # Variable +---| 14 # Constant +---| 15 # String +---| 16 # Number +---| 17 # Boolean +---| 18 # Array +---| 19 # Object +---| 20 # Key +---| 21 # Null +---| 22 # EnumMember +---| 23 # Struct +---| 24 # Event +---| 25 # Operator +---| 26 # TypeParameter + +---Symbol tags are extra annotations that tweak the rendering of a symbol. +--- +---@since 3.16 +---@alias lsp.SymbolTag +---| 1 # Deprecated + +---Moniker uniqueness level to define scope of the moniker. +--- +---@since 3.16.0 +---@alias lsp.UniquenessLevel +---| "document" # document +---| "project" # project +---| "group" # group +---| "scheme" # scheme +---| "global" # global + +---The moniker kind. +--- +---@since 3.16.0 +---@alias lsp.MonikerKind +---| "import" # import +---| "export" # export +---| "local" # local + +---Inlay hint kinds. +--- +---@since 3.17.0 +---@alias lsp.InlayHintKind +---| 1 # Type +---| 2 # Parameter + +---Defines whether the insert text in a completion item should be interpreted as +---plain text or a snippet. +---@alias lsp.InsertTextFormat +---| 1 # PlainText +---| 2 # Snippet + +---The message type +---@alias lsp.MessageType +---| 1 # Error +---| 2 # Warning +---| 3 # Info +---| 4 # Log + +---Defines how the host (editor) should sync +---document changes to the language server. +---@alias lsp.TextDocumentSyncKind +---| 0 # None +---| 1 # Full +---| 2 # Incremental + +---Represents reasons why a text document is saved. +---@alias lsp.TextDocumentSaveReason +---| 1 # Manual +---| 2 # AfterDelay +---| 3 # FocusOut + +---The kind of a completion entry. +---@alias lsp.CompletionItemKind +---| 1 # Text +---| 2 # Method +---| 3 # Function +---| 4 # Constructor +---| 5 # Field +---| 6 # Variable +---| 7 # Class +---| 8 # Interface +---| 9 # Module +---| 10 # Property +---| 11 # Unit +---| 12 # Value +---| 13 # Enum +---| 14 # Keyword +---| 15 # Snippet +---| 16 # Color +---| 17 # File +---| 18 # Reference +---| 19 # Folder +---| 20 # EnumMember +---| 21 # Constant +---| 22 # Struct +---| 23 # Event +---| 24 # Operator +---| 25 # TypeParameter + +---Completion item tags are extra annotations that tweak the rendering of a completion +---item. +--- +---@since 3.15.0 +---@alias lsp.CompletionItemTag +---| 1 # Deprecated + +---How whitespace and indentation is handled during completion +---item insertion. +--- +---@since 3.16.0 +---@alias lsp.InsertTextMode +---| 1 # asIs +---| 2 # adjustIndentation + +---A document highlight kind. +---@alias lsp.DocumentHighlightKind +---| 1 # Text +---| 2 # Read +---| 3 # Write + +---A set of predefined code action kinds +---@alias lsp.CodeActionKind +---| "" # Empty +---| "quickfix" # QuickFix +---| "refactor" # Refactor +---| "refactor.extract" # RefactorExtract +---| "refactor.inline" # RefactorInline +---| "refactor.rewrite" # RefactorRewrite +---| "source" # Source +---| "source.organizeImports" # SourceOrganizeImports +---| "source.fixAll" # SourceFixAll + +---@alias lsp.TraceValues +---| "off" # Off +---| "messages" # Messages +---| "verbose" # Verbose + +---Describes the content type that a client supports in various +---result literals like `Hover`, `ParameterInfo` or `CompletionItem`. +--- +---Please note that `MarkupKinds` must not start with a `$`. This kinds +---are reserved for internal usage. +---@alias lsp.MarkupKind +---| "plaintext" # PlainText +---| "markdown" # Markdown + +---Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. +--- +---@since 3.18.0 +---@alias lsp.InlineCompletionTriggerKind +---| 0 # Invoked +---| 1 # Automatic + +---A set of predefined position encoding kinds. +--- +---@since 3.17.0 +---@alias lsp.PositionEncodingKind +---| "utf-8" # UTF8 +---| "utf-16" # UTF16 +---| "utf-32" # UTF32 + +---The file event type +---@alias lsp.FileChangeType +---| 1 # Created +---| 2 # Changed +---| 3 # Deleted + +---@alias lsp.WatchKind +---| 1 # Create +---| 2 # Change +---| 4 # Delete + +---The diagnostic's severity. +---@alias lsp.DiagnosticSeverity +---| 1 # Error +---| 2 # Warning +---| 3 # Information +---| 4 # Hint + +---The diagnostic tags. +--- +---@since 3.15.0 +---@alias lsp.DiagnosticTag +---| 1 # Unnecessary +---| 2 # Deprecated + +---How a completion was triggered +---@alias lsp.CompletionTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # TriggerForIncompleteCompletions + +---How a signature help was triggered. +--- +---@since 3.15.0 +---@alias lsp.SignatureHelpTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # ContentChange + +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@alias lsp.CodeActionTriggerKind +---| 1 # Invoked +---| 2 # Automatic + +---A pattern kind describing if a glob pattern matches a file a folder or +---both. +--- +---@since 3.16.0 +---@alias lsp.FileOperationPatternKind +---| "file" # file +---| "folder" # folder + +---A notebook cell kind. +--- +---@since 3.17.0 +---@alias lsp.NotebookCellKind +---| 1 # Markup +---| 2 # Code + +---@alias lsp.ResourceOperationKind +---| "create" # Create +---| "rename" # Rename +---| "delete" # Delete + +---@alias lsp.FailureHandlingKind +---| "abort" # Abort +---| "transactional" # Transactional +---| "textOnlyTransactional" # TextOnlyTransactional +---| "undo" # Undo + +---@alias lsp.PrepareSupportDefaultBehavior +---| 1 # Identifier + +---@alias lsp.TokenFormat +---| "relative" # Relative + +---The definition of a symbol represented as one or many {@link Location locations}. +---For most programming languages there is only one location at which a symbol is +---defined. +--- +---Servers should prefer returning `DefinitionLink` over `Definition` if supported +---by the client. +---@alias lsp.Definition lsp.Location|lsp.Location[] + +---Information about where a symbol is defined. +--- +---Provides additional metadata over normal {@link Location location} definitions, including the range of +---the defining symbol +---@alias lsp.DefinitionLink lsp.LocationLink + +---LSP arrays. +---@since 3.17.0 +---@alias lsp.LSPArray lsp.LSPAny[] + +---The LSP any type. +---Please note that strictly speaking a property with the value `undefined` +---can't be converted into JSON preserving the property name. However for +---convenience it is allowed and assumed that all these properties are +---optional as well. +---@since 3.17.0 +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|integer|uinteger|decimal|boolean|lsp.null + +---The declaration of a symbol representation as one or many {@link Location locations}. +---@alias lsp.Declaration lsp.Location|lsp.Location[] + +---Information about where a symbol is declared. +--- +---Provides additional metadata over normal {@link Location location} declarations, including the range of +---the declaring symbol. +--- +---Servers should prefer returning `DeclarationLink` over `Declaration` if supported +---by the client. +---@alias lsp.DeclarationLink lsp.LocationLink + +---Inline value information can be provided by different means: +---- directly as a text value (class InlineValueText). +---- as a name to use for a variable lookup (class InlineValueVariableLookup) +---- as an evaluatable expression (class InlineValueEvaluatableExpression) +---The InlineValue types combines all inline value types into one type. +--- +---@since 3.17.0 +---@alias lsp.InlineValue lsp.InlineValueText|lsp.InlineValueVariableLookup|lsp.InlineValueEvaluatableExpression + +---The result of a document diagnostic pull request. A report can +---either be a full report containing all diagnostics for the +---requested document or an unchanged report indicating that nothing +---has changed in terms of diagnostics in comparison to the last +---pull request. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReport lsp.RelatedFullDocumentDiagnosticReport|lsp.RelatedUnchangedDocumentDiagnosticReport + +---@alias lsp.PrepareRenameResult lsp.Range|anonym44|anonym45 + +---A document selector is the combination of one or many document filters. +--- +---@sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`; +--- +---The use of a string as a document filter is deprecated @since 3.16.0. +---@alias lsp.DocumentSelector lsp.DocumentFilter[] + +---@alias lsp.ProgressToken integer|string + +---An identifier to refer to a change annotation stored with a workspace edit. +---@alias lsp.ChangeAnnotationIdentifier string + +---A workspace diagnostic document report. +--- +---@since 3.17.0 +---@alias lsp.WorkspaceDocumentDiagnosticReport lsp.WorkspaceFullDocumentDiagnosticReport|lsp.WorkspaceUnchangedDocumentDiagnosticReport + +---An event describing a change to a text document. If only a text is provided +---it is considered to be the full content of the document. +---@alias lsp.TextDocumentContentChangeEvent anonym46|anonym47 + +---MarkedString can be used to render human readable text. It is either a markdown string +---or a code-block that provides a language and a code snippet. The language identifier +---is semantically equal to the optional language identifier in fenced code blocks in GitHub +---issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---The pair of a language and a value is an equivalent to markdown: +---```${language} +---${value} +---``` +--- +---Note that markdown strings will be sanitized - that means html will be escaped. +---@deprecated use MarkupContent instead. +---@alias lsp.MarkedString string|anonym48 + +---A document filter describes a top level text document or +---a notebook cell document. +--- +---@since 3.17.0 - proposed support for NotebookCellTextDocumentFilter. +---@alias lsp.DocumentFilter lsp.TextDocumentFilter|lsp.NotebookCellTextDocumentFilter + +---LSP object definition. +---@since 3.17.0 +---@alias lsp.LSPObject table + +---The glob pattern. Either a string pattern or a relative pattern. +--- +---@since 3.17.0 +---@alias lsp.GlobPattern lsp.Pattern|lsp.RelativePattern + +---A document filter denotes a document by different properties like +---the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of +---its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}. +--- +---Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` +---@sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` +--- +---@since 3.17.0 +---@alias lsp.TextDocumentFilter anonym49|anonym50|anonym51 + +---A notebook document filter denotes a notebook document by +---different properties. The properties will be match +---against the notebook's URI (same as with documents) +--- +---@since 3.17.0 +---@alias lsp.NotebookDocumentFilter anonym52|anonym53|anonym54 + +---The glob pattern to watch relative to the base path. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@since 3.17.0 +---@alias lsp.Pattern string + +---@class anonym1 +---The name of the server as defined by the server. +---@field name string +---The server's version as defined by the server. +---@field version? string + +---@class anonym3 +---@field insert lsp.Range +---@field replace lsp.Range + +---@class anonym2 +---A default commit character set. +--- +---@since 3.17.0 +---@field commitCharacters? string[] +---A default edit range. +--- +---@since 3.17.0 +---@field editRange? lsp.Range|anonym3 +---A default insert text format. +--- +---@since 3.17.0 +---@field insertTextFormat? lsp.InsertTextFormat +---A default insert text mode. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---A default data value. +--- +---@since 3.17.0 +---@field data? lsp.LSPAny + +---@class anonym4 +---Human readable description of why the code action is currently disabled. +--- +---This is displayed in the code actions UI. +---@field reason string + +---@class anonym5 +---@field uri lsp.DocumentUri + +---@class anonym6 + +---@class anonym7 +---The server supports deltas for full documents. +---@field delta? boolean + +---@class anonym9 +---The change to the cell array. +---@field array lsp.NotebookCellArrayChange +---Additional opened cell text documents. +---@field didOpen? lsp.TextDocumentItem[] +---Additional closed cell text documents. +---@field didClose? lsp.TextDocumentIdentifier[] + +---@class anonym10 +---@field document lsp.VersionedTextDocumentIdentifier +---@field changes lsp.TextDocumentContentChangeEvent[] + +---@class anonym8 +---Changes to the cell structure to add or +---remove cells. +---@field structure? anonym9 +---Changes to notebook cells properties like its +---kind, execution summary or metadata. +---@field data? lsp.NotebookCell[] +---Changes to the text content of notebook cells. +---@field textContent? anonym10[] + +---@class anonym11 +---The name of the client as defined by the client. +---@field name string +---The client's version as defined by the client. +---@field version? string + +---@class anonym12 +---The server supports workspace folder. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFoldersServerCapabilities +---The server is interested in notifications/requests for operations on files. +--- +---@since 3.16.0 +---@field fileOperations? lsp.FileOperationOptions + +---@class anonym13 +---The server has support for completion item label +---details (see also `CompletionItemLabelDetails`) when +---receiving a completion item in a resolve call. +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym15 +---@field language string + +---@class anonym14 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells? anonym15[] + +---@class anonym17 +---@field language string + +---@class anonym16 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook? string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells anonym17[] + +---@class anonym18 +---The client will actively cancel the request. +---@field cancel boolean +---The list of requests for which the client +---will retry the request if it receives a +---response with error code `ContentModified` +---@field retryOnContentModified string[] + +---@class anonym19 +---Whether the client groups edits with equal labels into tree nodes, +---for instance all edits labelled with "Changes in Strings" would +---be a tree node. +---@field groupsOnLabel? boolean + +---@class anonym20 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym21 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym22 +---The properties that a client can resolve lazily. Usually +---`location.range` +---@field properties string[] + +---@class anonym24 +---The tags supported by the client. +---@field valueSet lsp.CompletionItemTag[] + +---@class anonym25 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym26 +---@field valueSet lsp.InsertTextMode[] + +---@class anonym23 +---Client supports snippets as insert text. +--- +---A snippet can define tab stops and placeholders with `$1`, `$2` +---and `${3:foo}`. `$0` defines the final tab stop, it defaults to +---the end of the snippet. Placeholders with equal identifiers are linked, +---that is typing in one will update others too. +---@field snippetSupport? boolean +---Client supports commit characters on a completion item. +---@field commitCharactersSupport? boolean +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client supports the deprecated property on a completion item. +---@field deprecatedSupport? boolean +---Client supports the preselect property on a completion item. +---@field preselectSupport? boolean +---Client supports the tag property on a completion item. Clients supporting +---tags have to handle unknown tags gracefully. Clients especially need to +---preserve unknown tags when sending a completion item back to the server in +---a resolve call. +--- +---@since 3.15.0 +---@field tagSupport? anonym24 +---Client support insert replace edit to control different behavior if a +---completion item is inserted in the text or should replace text. +--- +---@since 3.16.0 +---@field insertReplaceSupport? boolean +---Indicates which properties a client can resolve lazily on a completion +---item. Before version 3.16.0 only the predefined properties `documentation` +---and `details` could be resolved lazily. +--- +---@since 3.16.0 +---@field resolveSupport? anonym25 +---The client supports the `insertTextMode` property on +---a completion item to override the whitespace handling mode +---as defined by the client (see `insertTextMode`). +--- +---@since 3.16.0 +---@field insertTextModeSupport? anonym26 +---The client has support for completion item label +---details (see also `CompletionItemLabelDetails`). +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym27 +---The completion item kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the completion items kinds from `Text` to `Reference` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.CompletionItemKind[] + +---@class anonym28 +---The client supports the following itemDefaults on +---a completion list. +--- +---The value lists the supported property names of the +---`CompletionList.itemDefaults` object. If omitted +---no properties are supported. +--- +---@since 3.17.0 +---@field itemDefaults? string[] + +---@class anonym30 +---The client supports processing label offsets instead of a +---simple label string. +--- +---@since 3.14.0 +---@field labelOffsetSupport? boolean + +---@class anonym29 +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client capabilities specific to parameter information. +---@field parameterInformation? anonym30 +---The client supports the `activeParameter` property on `SignatureInformation` +---literal. +--- +---@since 3.16.0 +---@field activeParameterSupport? boolean + +---@class anonym31 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym32 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym34 +---The code action kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet lsp.CodeActionKind[] + +---@class anonym33 +---The code action kind is support with the following value +---set. +---@field codeActionKind anonym34 + +---@class anonym35 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym36 +---The folding range kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet? lsp.FoldingRangeKind[] + +---@class anonym37 +---If set, the client signals that it supports setting collapsedText on +---folding ranges to display custom labels instead of the default text. +--- +---@since 3.17.0 +---@field collapsedText? boolean + +---@class anonym38 +---The tags supported by the client. +---@field valueSet lsp.DiagnosticTag[] + +---@class anonym40 + +---@class anonym41 +---The client will send the `textDocument/semanticTokens/full/delta` request if +---the server provides a corresponding handler. +---@field delta? boolean + +---@class anonym39 +---The client will send the `textDocument/semanticTokens/range` request if +---the server provides a corresponding handler. +---@field range? boolean|anonym40 +---The client will send the `textDocument/semanticTokens/full` request if +---the server provides a corresponding handler. +---@field full? boolean|anonym41 + +---@class anonym42 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym43 +---Whether the client supports additional attributes which +---are preserved and send back to the server in the +---request's response. +---@field additionalPropertiesSupport? boolean + +---@class anonym44 +---@field range lsp.Range +---@field placeholder string + +---@class anonym45 +---@field defaultBehavior boolean + +---@class anonym46 +---The range of the document that changed. +---@field range lsp.Range +---The optional length of the range that got replaced. +--- +---@deprecated use range instead. +---@field rangeLength? uinteger +---The new text for the provided range. +---@field text string + +---@class anonym47 +---The new text of the whole document. +---@field text string + +---@class anonym48 +---@field language string +---@field value string + +---@class anonym49 +---A language id, like `typescript`. +---@field language string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym50 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym51 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern string + +---@class anonym52 +---The type of the enclosing notebook. +---@field notebookType string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern? string + +---@class anonym53 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern. +---@field pattern? string + +---@class anonym54 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern string diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 5dbd4a7199..1a4909b3f3 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -6,11 +6,13 @@ local lpeg = vim.lpeg local M = {} +---@alias lpeg userdata + --- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" --- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. --- ---@param pattern string The raw glob pattern ----@return userdata An |lpeg| representation of the pattern, or nil if the pattern is invalid. +---@return lpeg An |lpeg| representation of the pattern, or nil if the pattern is invalid. local function parse(pattern) local l = lpeg @@ -109,7 +111,7 @@ local to_lsp_change_type = { --- Default excludes the same as VSCode's `files.watcherExclude` setting. --- https://github.com/microsoft/vscode/blob/eef30e7165e19b33daa1e15e92fa34ff4a5df0d3/src/vs/workbench/contrib/files/browser/files.contribution.ts#L261 ----@type Lpeg pattern +---@type lpeg parsed Lpeg pattern M._poll_exclude_pattern = parse('**/.git/{objects,subtree-cache}/**') + parse('**/node_modules/*/**') + parse('**/.hg/store/**') @@ -132,7 +134,7 @@ function M.register(reg, ctx) if not has_capability or not client.workspace_folders then return end - local watch_regs = {} --- @type table + local watch_regs = {} --- @type table for _, w in ipairs(reg.registerOptions.watchers) do local relative_pattern = false local glob_patterns = {} --- @type {baseUri:string, pattern: string}[] diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index eb2f59b312..8407105d47 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -5,8 +5,8 @@ local api = vim.api local M = {} ---@class lsp.inlay_hint.bufstate ----@field version integer ----@field client_hint table> client_id -> (lnum -> hints) +---@field version? integer +---@field client_hint? table> client_id -> (lnum -> hints) ---@field applied table Last version of hints applied to this line ---@field enabled boolean Whether inlay hints are enabled for this buffer ---@type table diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index bab1b23ee4..5b20344bd3 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -14,11 +14,11 @@ local uv = vim.uv --- @field marked boolean whether this token has had extmarks applied --- --- @class STCurrentResult ---- @field version integer document version associated with this result ---- @field result_id string resultId from the server; used with delta requests ---- @field highlights STTokenRange[] cache of highlight ranges for this document version ---- @field tokens integer[] raw token array as received by the server. used for calculating delta responses ---- @field namespace_cleared boolean whether the namespace was cleared for this result yet +--- @field version? integer document version associated with this result +--- @field result_id? string resultId from the server; used with delta requests +--- @field highlights? STTokenRange[] cache of highlight ranges for this document version +--- @field tokens? integer[] raw token array as received by the server. used for calculating delta responses +--- @field namespace_cleared? boolean whether the namespace was cleared for this result yet --- --- @class STActiveRequest --- @field request_id integer the LSP request ID of the most recent request sent to the server @@ -717,8 +717,7 @@ end --- mark will be deleted by the semantic token engine when appropriate; for --- example, when the LSP sends updated tokens. This function is intended for --- use inside |LspTokenUpdate| callbacks. ----@param token (table) a semantic token, found as `args.data.token` in ---- |LspTokenUpdate|. +---@param token (table) a semantic token, found as `args.data.token` in |LspTokenUpdate|. ---@param bufnr (integer) the buffer to highlight ---@param client_id (integer) The ID of the |vim.lsp.client| ---@param hl_group (string) Highlight group name diff --git a/runtime/lua/vim/lsp/types.lua b/runtime/lua/vim/lsp/types.lua deleted file mode 100644 index 98e948c945..0000000000 --- a/runtime/lua/vim/lsp/types.lua +++ /dev/null @@ -1,21 +0,0 @@ ----@meta - ----@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil): any? - ----@class lsp.HandlerContext ----@field method string ----@field client_id integer ----@field bufnr? integer ----@field params? any - ----@class lsp.ResponseError ----@field code integer ----@field message string ----@field data string|number|boolean|table[]|table|nil - ---- @class lsp.DocumentFilter ---- @field language? string ---- @field scheme? string ---- @field pattern? string - ---- @alias lsp.RegisterOptions any | lsp.StaticRegistrationOptions | lsp.TextDocumentRegistrationOptions diff --git a/runtime/lua/vim/lsp/types/protocol.lua b/runtime/lua/vim/lsp/types/protocol.lua deleted file mode 100644 index e1ed8dbcc3..0000000000 --- a/runtime/lua/vim/lsp/types/protocol.lua +++ /dev/null @@ -1,4393 +0,0 @@ ---[[ -This file is autogenerated from scripts/gen_lsp.lua -Regenerate: -nvim -l scripts/gen_lsp.lua gen --version 3.18 --runtime/lua/vim/lsp/types/protocol.lua ---]] - ----@alias lsp.null nil ----@alias uinteger integer ----@alias lsp.decimal number ----@alias lsp.DocumentUri string ----@alias lsp.URI string ----@alias lsp.LSPObject table ----@alias lsp.LSPArray lsp.LSPAny[] ----@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|number|boolean|nil - ----@class lsp.ImplementationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----Represents a location inside a resource, such as a line ----inside a text file. ----@class lsp.Location ----@field uri lsp.DocumentUri ----@field range lsp.Range - ----@class lsp.ImplementationRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----@class lsp.TypeDefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----@class lsp.TypeDefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----A workspace folder inside a client. ----@class lsp.WorkspaceFolder ----The associated URI for this workspace folder. ----@field uri lsp.URI ----The name of the workspace folder. Used to refer to this ----workspace folder in the user interface. ----@field name string - ----The parameters of a `workspace/didChangeWorkspaceFolders` notification. ----@class lsp.DidChangeWorkspaceFoldersParams ----The actual workspace folder change event. ----@field event lsp.WorkspaceFoldersChangeEvent - ----The parameters of a configuration request. ----@class lsp.ConfigurationParams ----@field items lsp.ConfigurationItem[] - ----Parameters for a {@link DocumentColorRequest}. ----@class lsp.DocumentColorParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier - ----Represents a color range from a document. ----@class lsp.ColorInformation ----The range in the document where this color appears. ----@field range lsp.Range ----The actual color value for this color range. ----@field color lsp.Color - ----@class lsp.DocumentColorRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----Parameters for a {@link ColorPresentationRequest}. ----@class lsp.ColorPresentationParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The color to request presentations for. ----@field color lsp.Color ----The range where the color would be inserted. Serves as a context. ----@field range lsp.Range - ----@class lsp.ColorPresentation ----The label of this color presentation. It will be shown on the color ----picker header. By default this is also the text that is inserted when selecting ----this color presentation. ----@field label string ----An {@link TextEdit edit} which is applied to a document when selecting ----this presentation for the color. When `falsy` the {@link ColorPresentation.label label} ----is used. ----@field textEdit? lsp.TextEdit ----An optional array of additional {@link TextEdit text edits} that are applied when ----selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves. ----@field additionalTextEdits? lsp.TextEdit[] - ----@class lsp.WorkDoneProgressOptions ----@field workDoneProgress? boolean - ----General text document registration options. ----@class lsp.TextDocumentRegistrationOptions ----A document selector to identify the scope of the registration. If set to null ----the document selector provided on the client side will be used. ----@field documentSelector lsp.DocumentSelector|lsp.null - ----Parameters for a {@link FoldingRangeRequest}. ----@class lsp.FoldingRangeParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier - ----Represents a folding range. To be valid, start and end line must be bigger than zero and smaller ----than the number of lines in the document. Clients are free to ignore invalid ranges. ----@class lsp.FoldingRange ----The zero-based start line of the range to fold. The folded area starts after the line's last character. ----To be valid, the end must be zero or larger and smaller than the number of lines in the document. ----@field startLine uinteger ----The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. ----@field startCharacter? uinteger ----The zero-based end line of the range to fold. The folded area ends with the line's last character. ----To be valid, the end must be zero or larger and smaller than the number of lines in the document. ----@field endLine uinteger ----The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. ----@field endCharacter? uinteger ----Describes the kind of the folding range such as `comment' or 'region'. The kind ----is used to categorize folding ranges and used by commands like 'Fold all comments'. ----See {@link FoldingRangeKind} for an enumeration of standardized kinds. ----@field kind? lsp.FoldingRangeKind ----The text that the client should show when the specified range is ----collapsed. If not defined or not supported by the client, a default ----will be chosen by the client. ---- ----@since 3.17.0 ----@field collapsedText? string - ----@class lsp.FoldingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----@class lsp.DeclarationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----@class lsp.DeclarationRegistrationOptions: lsp.DeclarationOptions, lsp.StaticRegistrationOptions - ----A parameter literal used in selection range requests. ----@class lsp.SelectionRangeParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The positions inside the text document. ----@field positions lsp.Position[] - ----A selection range represents a part of a selection hierarchy. A selection range ----may have a parent selection range that contains it. ----@class lsp.SelectionRange ----The {@link Range range} of this selection range. ----@field range lsp.Range ----The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. ----@field parent? lsp.SelectionRange - ----@class lsp.SelectionRangeRegistrationOptions: lsp.SelectionRangeOptions, lsp.StaticRegistrationOptions - ----@class lsp.WorkDoneProgressCreateParams ----The token to be used to report progress. ----@field token lsp.ProgressToken - ----@class lsp.WorkDoneProgressCancelParams ----The token to be used to report progress. ----@field token lsp.ProgressToken - ----The parameter of a `textDocument/prepareCallHierarchy` request. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams - ----Represents programming constructs like functions or constructors in the context ----of call hierarchy. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyItem ----The name of this item. ----@field name string ----The kind of this item. ----@field kind lsp.SymbolKind ----Tags for this item. ----@field tags? lsp.SymbolTag[] ----More detail for this item, e.g. the signature of a function. ----@field detail? string ----The resource identifier of this item. ----@field uri lsp.DocumentUri ----The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. ----@field range lsp.Range ----The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. ----Must be contained by the {@link CallHierarchyItem.range `range`}. ----@field selectionRange lsp.Range ----A data entry field that is preserved between a call hierarchy prepare and ----incoming calls or outgoing calls requests. ----@field data? lsp.LSPAny - ----Call hierarchy options used during static or dynamic registration. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----The parameter of a `callHierarchy/incomingCalls` request. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyIncomingCallsParams ----@field item lsp.CallHierarchyItem - ----Represents an incoming call, e.g. a caller of a method or constructor. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyIncomingCall ----The item that makes the call. ----@field from lsp.CallHierarchyItem ----The ranges at which the calls appear. This is relative to the caller ----denoted by {@link CallHierarchyIncomingCall.from `this.from`}. ----@field fromRanges lsp.Range[] - ----The parameter of a `callHierarchy/outgoingCalls` request. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyOutgoingCallsParams ----@field item lsp.CallHierarchyItem - ----Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyOutgoingCall ----The item that is called. ----@field to lsp.CallHierarchyItem ----The range at which this item is called. This is the range relative to the caller, e.g the item ----passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} ----and not {@link CallHierarchyOutgoingCall.to `this.to`}. ----@field fromRanges lsp.Range[] - ----@since 3.16.0 ----@class lsp.SemanticTokensParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier - ----@since 3.16.0 ----@class lsp.SemanticTokens ----An optional result id. If provided and clients support delta updating ----the client will include the result id in the next semantic token request. ----A server can then instead of computing all semantic tokens again simply ----send a delta. ----@field resultId? string ----The actual tokens. ----@field data uinteger[] - ----@since 3.16.0 ----@class lsp.SemanticTokensPartialResult ----@field data uinteger[] - ----@since 3.16.0 ----@class lsp.SemanticTokensRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----@since 3.16.0 ----@class lsp.SemanticTokensDeltaParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The result id of a previous response. The result Id can either point to a full response ----or a delta response depending on what was received last. ----@field previousResultId string - ----@since 3.16.0 ----@class lsp.SemanticTokensDelta ----@field resultId? string ----The semantic token edits to transform a previous result into a new result. ----@field edits lsp.SemanticTokensEdit[] - ----@since 3.16.0 ----@class lsp.SemanticTokensDeltaPartialResult ----@field edits lsp.SemanticTokensEdit[] - ----@since 3.16.0 ----@class lsp.SemanticTokensRangeParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The range the semantic tokens are requested for. ----@field range lsp.Range - ----Params to show a resource in the UI. ---- ----@since 3.16.0 ----@class lsp.ShowDocumentParams ----The uri to show. ----@field uri lsp.URI ----Indicates to show the resource in an external program. ----To show, for example, `https://code.visualstudio.com/` ----in the default WEB browser set `external` to `true`. ----@field external? boolean ----An optional property to indicate whether the editor ----showing the document should take focus or not. ----Clients might ignore this property if an external ----program is started. ----@field takeFocus? boolean ----An optional selection range if the document is a text ----document. Clients might ignore the property if an ----external program is started or the file is not a text ----file. ----@field selection? lsp.Range - ----The result of a showDocument request. ---- ----@since 3.16.0 ----@class lsp.ShowDocumentResult ----A boolean indicating if the show was successful. ----@field success boolean - ----@class lsp.LinkedEditingRangeParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams - ----The result of a linked editing range request. ---- ----@since 3.16.0 ----@class lsp.LinkedEditingRanges ----A list of ranges that can be edited together. The ranges must have ----identical length and contain identical text content. The ranges cannot overlap. ----@field ranges lsp.Range[] ----An optional word pattern (regular expression) that describes valid contents for ----the given ranges. If no pattern is provided, the client configuration's word ----pattern will be used. ----@field wordPattern? string - ----@class lsp.LinkedEditingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----The parameters sent in notifications/requests for user-initiated creation of ----files. ---- ----@since 3.16.0 ----@class lsp.CreateFilesParams ----An array of all files/folders created in this operation. ----@field files lsp.FileCreate[] - ----A workspace edit represents changes to many resources managed in the workspace. The edit ----should either provide `changes` or `documentChanges`. If documentChanges are present ----they are preferred over `changes` if the client can handle versioned document edits. ---- ----Since version 3.13.0 a workspace edit can contain resource operations as well. If resource ----operations are present clients need to execute the operations in the order in which they ----are provided. So a workspace edit for example can consist of the following two changes: ----(1) a create file a.txt and (2) a text document edit which insert text into file a.txt. ---- ----An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will ----cause failure of the operation. How the client recovers from the failure is described by ----the client capability: `workspace.workspaceEdit.failureHandling` ----@class lsp.WorkspaceEdit ----Holds changes to existing resources. ----@field changes? table ----Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes ----are either an array of `TextDocumentEdit`s to express changes to n different text documents ----where each text document edit addresses a specific version of a text document. Or it can contain ----above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. ---- ----Whether a client supports versioned document edits is expressed via ----`workspace.workspaceEdit.documentChanges` client capability. ---- ----If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then ----only plain `TextEdit`s using the `changes` property are supported. ----@field documentChanges? lsp.TextDocumentEdit|lsp.CreateFile|lsp.RenameFile|lsp.DeleteFile[] ----A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and ----delete file / folder operations. ---- ----Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. ---- ----@since 3.16.0 ----@field changeAnnotations? table - ----The options to register for file operations. ---- ----@since 3.16.0 ----@class lsp.FileOperationRegistrationOptions ----The actual filters. ----@field filters lsp.FileOperationFilter[] - ----The parameters sent in notifications/requests for user-initiated renames of ----files. ---- ----@since 3.16.0 ----@class lsp.RenameFilesParams ----An array of all files/folders renamed in this operation. When a folder is renamed, only ----the folder will be included, and not its children. ----@field files lsp.FileRename[] - ----The parameters sent in notifications/requests for user-initiated deletes of ----files. ---- ----@since 3.16.0 ----@class lsp.DeleteFilesParams ----An array of all files/folders deleted in this operation. ----@field files lsp.FileDelete[] - ----@class lsp.MonikerParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----Moniker definition to match LSIF 0.5 moniker definition. ---- ----@since 3.16.0 ----@class lsp.Moniker ----The scheme of the moniker. For example tsc or .Net ----@field scheme string ----The identifier of the moniker. The value is opaque in LSIF however ----schema owners are allowed to define the structure if they want. ----@field identifier string ----The scope in which the moniker is unique ----@field unique lsp.UniquenessLevel ----The moniker kind if known. ----@field kind? lsp.MonikerKind - ----@class lsp.MonikerRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameter of a `textDocument/prepareTypeHierarchy` request. ---- ----@since 3.17.0 ----@class lsp.TypeHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams - ----@since 3.17.0 ----@class lsp.TypeHierarchyItem ----The name of this item. ----@field name string ----The kind of this item. ----@field kind lsp.SymbolKind ----Tags for this item. ----@field tags? lsp.SymbolTag[] ----More detail for this item, e.g. the signature of a function. ----@field detail? string ----The resource identifier of this item. ----@field uri lsp.DocumentUri ----The range enclosing this symbol not including leading/trailing whitespace ----but everything else, e.g. comments and code. ----@field range lsp.Range ----The range that should be selected and revealed when this symbol is being ----picked, e.g. the name of a function. Must be contained by the ----{@link TypeHierarchyItem.range `range`}. ----@field selectionRange lsp.Range ----A data entry field that is preserved between a type hierarchy prepare and ----supertypes or subtypes requests. It could also be used to identify the ----type hierarchy in the server, helping improve the performance on ----resolving supertypes and subtypes. ----@field data? lsp.LSPAny - ----Type hierarchy options used during static or dynamic registration. ---- ----@since 3.17.0 ----@class lsp.TypeHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----The parameter of a `typeHierarchy/supertypes` request. ---- ----@since 3.17.0 ----@class lsp.TypeHierarchySupertypesParams ----@field item lsp.TypeHierarchyItem - ----The parameter of a `typeHierarchy/subtypes` request. ---- ----@since 3.17.0 ----@class lsp.TypeHierarchySubtypesParams ----@field item lsp.TypeHierarchyItem - ----A parameter literal used in inline value requests. ---- ----@since 3.17.0 ----@class lsp.InlineValueParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The document range for which inline values should be computed. ----@field range lsp.Range ----Additional information about the context in which inline values were ----requested. ----@field context lsp.InlineValueContext - ----Inline value options used during static or dynamic registration. ---- ----@since 3.17.0 ----@class lsp.InlineValueRegistrationOptions: lsp.InlineValueOptions, lsp.StaticRegistrationOptions - ----A parameter literal used in inlay hint requests. ---- ----@since 3.17.0 ----@class lsp.InlayHintParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The document range for which inlay hints should be computed. ----@field range lsp.Range - ----Inlay hint information. ---- ----@since 3.17.0 ----@class lsp.InlayHint ----The position of this hint. ----@field position lsp.Position ----The label of this hint. A human readable string or an array of ----InlayHintLabelPart label parts. ---- ----*Note* that neither the string nor the label part can be empty. ----@field label string|lsp.InlayHintLabelPart[] ----The kind of this hint. Can be omitted in which case the client ----should fall back to a reasonable default. ----@field kind? lsp.InlayHintKind ----Optional text edits that are performed when accepting this inlay hint. ---- ----*Note* that edits are expected to change the document so that the inlay ----hint (or its nearest variant) is now part of the document and the inlay ----hint itself is now obsolete. ----@field textEdits? lsp.TextEdit[] ----The tooltip text when you hover over this item. ----@field tooltip? string|lsp.MarkupContent ----Render padding before the hint. ---- ----Note: Padding should use the editor's background color, not the ----background color of the hint itself. That means padding can be used ----to visually align/separate an inlay hint. ----@field paddingLeft? boolean ----Render padding after the hint. ---- ----Note: Padding should use the editor's background color, not the ----background color of the hint itself. That means padding can be used ----to visually align/separate an inlay hint. ----@field paddingRight? boolean ----A data entry field that is preserved on an inlay hint between ----a `textDocument/inlayHint` and a `inlayHint/resolve` request. ----@field data? lsp.LSPAny - ----Inlay hint options used during static or dynamic registration. ---- ----@since 3.17.0 ----@class lsp.InlayHintRegistrationOptions: lsp.InlayHintOptions, lsp.StaticRegistrationOptions - ----Parameters of the document diagnostic request. ---- ----@since 3.17.0 ----@class lsp.DocumentDiagnosticParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The additional identifier provided during registration. ----@field identifier? string ----The result id of a previous response if provided. ----@field previousResultId? string - ----A partial result for a document diagnostic report. ---- ----@since 3.17.0 ----@class lsp.DocumentDiagnosticReportPartialResult ----@field relatedDocuments table - ----Cancellation data returned from a diagnostic request. ---- ----@since 3.17.0 ----@class lsp.DiagnosticServerCancellationData ----@field retriggerRequest boolean - ----Diagnostic registration options. ---- ----@since 3.17.0 ----@class lsp.DiagnosticRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions - ----Parameters of the workspace diagnostic request. ---- ----@since 3.17.0 ----@class lsp.WorkspaceDiagnosticParams ----The additional identifier provided during registration. ----@field identifier? string ----The currently known diagnostic reports with their ----previous result ids. ----@field previousResultIds lsp.PreviousResultId[] - ----A workspace diagnostic report. ---- ----@since 3.17.0 ----@class lsp.WorkspaceDiagnosticReport ----@field items lsp.WorkspaceDocumentDiagnosticReport[] - ----A partial result for a workspace diagnostic report. ---- ----@since 3.17.0 ----@class lsp.WorkspaceDiagnosticReportPartialResult ----@field items lsp.WorkspaceDocumentDiagnosticReport[] - ----The params sent in an open notebook document notification. ---- ----@since 3.17.0 ----@class lsp.DidOpenNotebookDocumentParams ----The notebook document that got opened. ----@field notebookDocument lsp.NotebookDocument ----The text documents that represent the content ----of a notebook cell. ----@field cellTextDocuments lsp.TextDocumentItem[] - ----The params sent in a change notebook document notification. ---- ----@since 3.17.0 ----@class lsp.DidChangeNotebookDocumentParams ----The notebook document that did change. The version number points ----to the version after all provided changes have been applied. If ----only the text document content of a cell changes the notebook version ----doesn't necessarily have to change. ----@field notebookDocument lsp.VersionedNotebookDocumentIdentifier ----The actual changes to the notebook document. ---- ----The changes describe single state changes to the notebook document. ----So if there are two changes c1 (at array index 0) and c2 (at array ----index 1) for a notebook in state S then c1 moves the notebook from ----S to S' and c2 from S' to S''. So c1 is computed on the state S and ----c2 is computed on the state S'. ---- ----To mirror the content of a notebook using change events use the following approach: ----- start with the same initial content ----- apply the 'notebookDocument/didChange' notifications in the order you receive them. ----- apply the `NotebookChangeEvent`s in a single notification in the order ---- you receive them. ----@field change lsp.NotebookDocumentChangeEvent - ----The params sent in a save notebook document notification. ---- ----@since 3.17.0 ----@class lsp.DidSaveNotebookDocumentParams ----The notebook document that got saved. ----@field notebookDocument lsp.NotebookDocumentIdentifier - ----The params sent in a close notebook document notification. ---- ----@since 3.17.0 ----@class lsp.DidCloseNotebookDocumentParams ----The notebook document that got closed. ----@field notebookDocument lsp.NotebookDocumentIdentifier ----The text documents that represent the content ----of a notebook cell that got closed. ----@field cellTextDocuments lsp.TextDocumentIdentifier[] - ----A parameter literal used in inline completion requests. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams ----Additional information about the context in which inline completions were ----requested. ----@field context lsp.InlineCompletionContext - ----Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. ----@class lsp.InlineCompletionList ----The inline completion items ----@field items lsp.InlineCompletionItem[] - ----An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionItem ----The text to replace the range with. Must be set. ----@field insertText string ----The format of the insert text. The format applies to the `insertText`. If omitted defaults to `InsertTextFormat.PlainText`. ----@field insertTextFormat? lsp.InsertTextFormat ----A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. ----@field filterText? string ----The range to replace. Must begin and end on the same line. ----@field range? lsp.Range ----An optional {@link Command} that is executed *after* inserting this completion. ----@field command? lsp.Command - ----Inline completion options used during static or dynamic registration. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionRegistrationOptions: lsp.InlineCompletionOptions, lsp.StaticRegistrationOptions - ----@class lsp.RegistrationParams ----@field registrations lsp.Registration[] - ----@class lsp.UnregistrationParams ----@field unregisterations lsp.Unregistration[] - ----@class lsp.InitializeParams: lsp._InitializeParams - ----The result returned from an initialize request. ----@class lsp.InitializeResult ----The capabilities the language server provides. ----@field capabilities lsp.ServerCapabilities ----Information about the server. ---- ----@since 3.15.0 ----@field serverInfo? anonym1 - ----The data type of the ResponseError if the ----initialize request fails. ----@class lsp.InitializeError ----Indicates whether the client execute the following retry logic: ----(1) show the message provided by the ResponseError to the user ----(2) user selects retry or cancel ----(3) if user selected retry the initialize method is sent again. ----@field retry boolean - ----@class lsp.InitializedParams - ----The parameters of a change configuration notification. ----@class lsp.DidChangeConfigurationParams ----The actual changed settings ----@field settings lsp.LSPAny - ----@class lsp.DidChangeConfigurationRegistrationOptions ----@field section? string|string[] - ----The parameters of a notification message. ----@class lsp.ShowMessageParams ----The message type. See {@link MessageType} ----@field type lsp.MessageType ----The actual message. ----@field message string - ----@class lsp.ShowMessageRequestParams ----The message type. See {@link MessageType} ----@field type lsp.MessageType ----The actual message. ----@field message string ----The message action items to present. ----@field actions? lsp.MessageActionItem[] - ----@class lsp.MessageActionItem ----A short title like 'Retry', 'Open Log' etc. ----@field title string - ----The log message parameters. ----@class lsp.LogMessageParams ----The message type. See {@link MessageType} ----@field type lsp.MessageType ----The actual message. ----@field message string - ----The parameters sent in an open text document notification ----@class lsp.DidOpenTextDocumentParams ----The document that was opened. ----@field textDocument lsp.TextDocumentItem - ----The change text document notification's parameters. ----@class lsp.DidChangeTextDocumentParams ----The document that did change. The version number points ----to the version after all provided content changes have ----been applied. ----@field textDocument lsp.VersionedTextDocumentIdentifier ----The actual content changes. The content changes describe single state changes ----to the document. So if there are two content changes c1 (at array index 0) and ----c2 (at array index 1) for a document in state S then c1 moves the document from ----S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed ----on the state S'. ---- ----To mirror the content of a document using change events use the following approach: ----- start with the same initial content ----- apply the 'textDocument/didChange' notifications in the order you receive them. ----- apply the `TextDocumentContentChangeEvent`s in a single notification in the order ---- you receive them. ----@field contentChanges lsp.TextDocumentContentChangeEvent[] - ----Describe options to be used when registered for text document change events. ----@class lsp.TextDocumentChangeRegistrationOptions: lsp.TextDocumentRegistrationOptions ----How documents are synced to the server. ----@field syncKind lsp.TextDocumentSyncKind - ----The parameters sent in a close text document notification ----@class lsp.DidCloseTextDocumentParams ----The document that was closed. ----@field textDocument lsp.TextDocumentIdentifier - ----The parameters sent in a save text document notification ----@class lsp.DidSaveTextDocumentParams ----The document that was saved. ----@field textDocument lsp.TextDocumentIdentifier ----Optional the content when saved. Depends on the includeText value ----when the save notification was requested. ----@field text? string - ----Save registration options. ----@class lsp.TextDocumentSaveRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters sent in a will save text document notification. ----@class lsp.WillSaveTextDocumentParams ----The document that will be saved. ----@field textDocument lsp.TextDocumentIdentifier ----The 'TextDocumentSaveReason'. ----@field reason lsp.TextDocumentSaveReason - ----A text edit applicable to a text document. ----@class lsp.TextEdit ----The range of the text document to be manipulated. To insert ----text into a document create a range where start === end. ----@field range lsp.Range ----The string to be inserted. For delete operations use an ----empty string. ----@field newText string - ----The watched files change notification's parameters. ----@class lsp.DidChangeWatchedFilesParams ----The actual file events. ----@field changes lsp.FileEvent[] - ----Describe options to be used when registered for text document change events. ----@class lsp.DidChangeWatchedFilesRegistrationOptions ----The watchers to register. ----@field watchers lsp.FileSystemWatcher[] - ----The publish diagnostic notification's parameters. ----@class lsp.PublishDiagnosticsParams ----The URI for which diagnostic information is reported. ----@field uri lsp.DocumentUri ----Optional the version number of the document the diagnostics are published for. ---- ----@since 3.15.0 ----@field version? integer ----An array of diagnostic information items. ----@field diagnostics lsp.Diagnostic[] - ----Completion parameters ----@class lsp.CompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams ----The completion context. This is only available it the client specifies ----to send this using the client capability `textDocument.completion.contextSupport === true` ----@field context? lsp.CompletionContext - ----A completion item represents a text snippet that is ----proposed to complete text that is being typed. ----@class lsp.CompletionItem ----The label of this completion item. ---- ----The label property is also by default the text that ----is inserted when selecting this completion. ---- ----If label details are provided the label itself should ----be an unqualified name of the completion item. ----@field label string ----Additional details for the label ---- ----@since 3.17.0 ----@field labelDetails? lsp.CompletionItemLabelDetails ----The kind of this completion item. Based of the kind ----an icon is chosen by the editor. ----@field kind? lsp.CompletionItemKind ----Tags for this completion item. ---- ----@since 3.15.0 ----@field tags? lsp.CompletionItemTag[] ----A human-readable string with additional information ----about this item, like type or symbol information. ----@field detail? string ----A human-readable string that represents a doc-comment. ----@field documentation? string|lsp.MarkupContent ----Indicates if this item is deprecated. ----@deprecated Use `tags` instead. ----@field deprecated? boolean ----Select this item when showing. ---- ----*Note* that only one completion item can be selected and that the ----tool / client decides which item that is. The rule is that the *first* ----item of those that match best is selected. ----@field preselect? boolean ----A string that should be used when comparing this item ----with other items. When `falsy` the {@link CompletionItem.label label} ----is used. ----@field sortText? string ----A string that should be used when filtering a set of ----completion items. When `falsy` the {@link CompletionItem.label label} ----is used. ----@field filterText? string ----A string that should be inserted into a document when selecting ----this completion. When `falsy` the {@link CompletionItem.label label} ----is used. ---- ----The `insertText` is subject to interpretation by the client side. ----Some tools might not take the string literally. For example ----VS Code when code complete is requested in this example ----`con` and a completion item with an `insertText` of ----`console` is provided it will only insert `sole`. Therefore it is ----recommended to use `textEdit` instead since it avoids additional client ----side interpretation. ----@field insertText? string ----The format of the insert text. The format applies to both the ----`insertText` property and the `newText` property of a provided ----`textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. ---- ----Please note that the insertTextFormat doesn't apply to ----`additionalTextEdits`. ----@field insertTextFormat? lsp.InsertTextFormat ----How whitespace and indentation is handled during completion ----item insertion. If not provided the clients default value depends on ----the `textDocument.completion.insertTextMode` client capability. ---- ----@since 3.16.0 ----@field insertTextMode? lsp.InsertTextMode ----An {@link TextEdit edit} which is applied to a document when selecting ----this completion. When an edit is provided the value of ----{@link CompletionItem.insertText insertText} is ignored. ---- ----Most editors support two different operations when accepting a completion ----item. One is to insert a completion text and the other is to replace an ----existing text with a completion text. Since this can usually not be ----predetermined by a server it can report both ranges. Clients need to ----signal support for `InsertReplaceEdits` via the ----`textDocument.completion.insertReplaceSupport` client capability ----property. ---- ----*Note 1:* The text edit's range as well as both ranges from an insert ----replace edit must be a [single line] and they must contain the position ----at which completion has been requested. ----*Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range ----must be a prefix of the edit's replace range, that means it must be ----contained and starting at the same position. ---- ----@since 3.16.0 additional type `InsertReplaceEdit` ----@field textEdit? lsp.TextEdit|lsp.InsertReplaceEdit ----The edit text used if the completion item is part of a CompletionList and ----CompletionList defines an item default for the text edit range. ---- ----Clients will only honor this property if they opt into completion list ----item defaults using the capability `completionList.itemDefaults`. ---- ----If not provided and a list's default range is provided the label ----property is used as a text. ---- ----@since 3.17.0 ----@field textEditText? string ----An optional array of additional {@link TextEdit text edits} that are applied when ----selecting this completion. Edits must not overlap (including the same insert position) ----with the main {@link CompletionItem.textEdit edit} nor with themselves. ---- ----Additional text edits should be used to change text unrelated to the current cursor position ----(for example adding an import statement at the top of the file if the completion item will ----insert an unqualified type). ----@field additionalTextEdits? lsp.TextEdit[] ----An optional set of characters that when pressed while this completion is active will accept it first and ----then type that character. *Note* that all commit characters should have `length=1` and that superfluous ----characters will be ignored. ----@field commitCharacters? string[] ----An optional {@link Command command} that is executed *after* inserting this completion. *Note* that ----additional modifications to the current document should be described with the ----{@link CompletionItem.additionalTextEdits additionalTextEdits}-property. ----@field command? lsp.Command ----A data entry field that is preserved on a completion item between a ----{@link CompletionRequest} and a {@link CompletionResolveRequest}. ----@field data? lsp.LSPAny - ----Represents a collection of {@link CompletionItem completion items} to be presented ----in the editor. ----@class lsp.CompletionList ----This list it not complete. Further typing results in recomputing this list. ---- ----Recomputed lists have all their items replaced (not appended) in the ----incomplete completion sessions. ----@field isIncomplete boolean ----In many cases the items of an actual completion result share the same ----value for properties like `commitCharacters` or the range of a text ----edit. A completion list can therefore define item defaults which will ----be used if a completion item itself doesn't specify the value. ---- ----If a completion list specifies a default value and a completion item ----also specifies a corresponding value the one from the item is used. ---- ----Servers are only allowed to return default values if the client ----signals support for this via the `completionList.itemDefaults` ----capability. ---- ----@since 3.17.0 ----@field itemDefaults? anonym3 ----The completion items. ----@field items lsp.CompletionItem[] - ----Registration options for a {@link CompletionRequest}. ----@class lsp.CompletionRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link HoverRequest}. ----@class lsp.HoverParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams - ----The result of a hover request. ----@class lsp.Hover ----The hover's content ----@field contents lsp.MarkupContent|lsp.MarkedString|lsp.MarkedString[] ----An optional range inside the text document that is used to ----visualize the hover, e.g. by changing the background color. ----@field range? lsp.Range - ----Registration options for a {@link HoverRequest}. ----@class lsp.HoverRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link SignatureHelpRequest}. ----@class lsp.SignatureHelpParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams ----The signature help context. This is only available if the client specifies ----to send this using the client capability `textDocument.signatureHelp.contextSupport === true` ---- ----@since 3.15.0 ----@field context? lsp.SignatureHelpContext - ----Signature help represents the signature of something ----callable. There can be multiple signature but only one ----active and only one active parameter. ----@class lsp.SignatureHelp ----One or more signatures. ----@field signatures lsp.SignatureInformation[] ----The active signature. If omitted or the value lies outside the ----range of `signatures` the value defaults to zero or is ignored if ----the `SignatureHelp` has no signatures. ---- ----Whenever possible implementors should make an active decision about ----the active signature and shouldn't rely on a default value. ---- ----In future version of the protocol this property might become ----mandatory to better express this. ----@field activeSignature? uinteger ----The active parameter of the active signature. If omitted or the value ----lies outside the range of `signatures[activeSignature].parameters` ----defaults to 0 if the active signature has parameters. If ----the active signature has no parameters it is ignored. ----In future version of the protocol this property might become ----mandatory to better express the active parameter if the ----active signature does have any. ----@field activeParameter? uinteger - ----Registration options for a {@link SignatureHelpRequest}. ----@class lsp.SignatureHelpRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link DefinitionRequest}. ----@class lsp.DefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----Registration options for a {@link DefinitionRequest}. ----@class lsp.DefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link ReferencesRequest}. ----@class lsp.ReferenceParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams ----@field context lsp.ReferenceContext - ----Registration options for a {@link ReferencesRequest}. ----@class lsp.ReferenceRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link DocumentHighlightRequest}. ----@class lsp.DocumentHighlightParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams - ----A document highlight is a range inside a text document which deserves ----special attention. Usually a document highlight is visualized by changing ----the background color of its range. ----@class lsp.DocumentHighlight ----The range this highlight applies to. ----@field range lsp.Range ----The highlight kind, default is {@link DocumentHighlightKind.Text text}. ----@field kind? lsp.DocumentHighlightKind - ----Registration options for a {@link DocumentHighlightRequest}. ----@class lsp.DocumentHighlightRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----Parameters for a {@link DocumentSymbolRequest}. ----@class lsp.DocumentSymbolParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier - ----Represents information about programming constructs like variables, classes, ----interfaces etc. ----@class lsp.SymbolInformation: lsp.BaseSymbolInformation ----Indicates if this symbol is deprecated. ---- ----@deprecated Use tags instead ----@field deprecated? boolean ----The location of this symbol. The location's range is used by a tool ----to reveal the location in the editor. If the symbol is selected in the ----tool the range's start information is used to position the cursor. So ----the range usually spans more than the actual symbol's name and does ----normally include things like visibility modifiers. ---- ----The range doesn't have to denote a node range in the sense of an abstract ----syntax tree. It can therefore not be used to re-construct a hierarchy of ----the symbols. ----@field location lsp.Location - ----Represents programming constructs like variables, classes, interfaces etc. ----that appear in a document. Document symbols can be hierarchical and they ----have two ranges: one that encloses its definition and one that points to ----its most interesting range, e.g. the range of an identifier. ----@class lsp.DocumentSymbol ----The name of this symbol. Will be displayed in the user interface and therefore must not be ----an empty string or a string only consisting of white spaces. ----@field name string ----More detail for this symbol, e.g the signature of a function. ----@field detail? string ----The kind of this symbol. ----@field kind lsp.SymbolKind ----Tags for this document symbol. ---- ----@since 3.16.0 ----@field tags? lsp.SymbolTag[] ----Indicates if this symbol is deprecated. ---- ----@deprecated Use tags instead ----@field deprecated? boolean ----The range enclosing this symbol not including leading/trailing whitespace but everything else ----like comments. This information is typically used to determine if the clients cursor is ----inside the symbol to reveal in the symbol in the UI. ----@field range lsp.Range ----The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. ----Must be contained by the `range`. ----@field selectionRange lsp.Range ----Children of this symbol, e.g. properties of a class. ----@field children? lsp.DocumentSymbol[] - ----Registration options for a {@link DocumentSymbolRequest}. ----@class lsp.DocumentSymbolRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link CodeActionRequest}. ----@class lsp.CodeActionParams ----The document in which the command was invoked. ----@field textDocument lsp.TextDocumentIdentifier ----The range for which the command was invoked. ----@field range lsp.Range ----Context carrying additional information. ----@field context lsp.CodeActionContext - ----Represents a reference to a command. Provides a title which ----will be used to represent a command in the UI and, optionally, ----an array of arguments which will be passed to the command handler ----function when invoked. ----@class lsp.Command ----Title of the command, like `save`. ----@field title string ----The identifier of the actual command handler. ----@field command string ----Arguments that the command handler should be ----invoked with. ----@field arguments? lsp.LSPAny[] - ----A code action represents a change that can be performed in code, e.g. to fix a problem or ----to refactor code. ---- ----A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. ----@class lsp.CodeAction ----A short, human-readable, title for this code action. ----@field title string ----The kind of the code action. ---- ----Used to filter code actions. ----@field kind? lsp.CodeActionKind ----The diagnostics that this code action resolves. ----@field diagnostics? lsp.Diagnostic[] ----Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted ----by keybindings. ---- ----A quick fix should be marked preferred if it properly addresses the underlying error. ----A refactoring should be marked preferred if it is the most reasonable choice of actions to take. ---- ----@since 3.15.0 ----@field isPreferred? boolean ----Marks that the code action cannot currently be applied. ---- ----Clients should follow the following guidelines regarding disabled code actions: ---- ---- - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) ---- code action menus. ---- ---- - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type ---- of code action, such as refactorings. ---- ---- - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) ---- that auto applies a code action and only disabled code actions are returned, the client should show the user an ---- error message with `reason` in the editor. ---- ----@since 3.16.0 ----@field disabled? anonym4 ----The workspace edit this code action performs. ----@field edit? lsp.WorkspaceEdit ----A command this code action executes. If a code action ----provides an edit and a command, first the edit is ----executed and then the command. ----@field command? lsp.Command ----A data entry field that is preserved on a code action between ----a `textDocument/codeAction` and a `codeAction/resolve` request. ---- ----@since 3.16.0 ----@field data? lsp.LSPAny - ----Registration options for a {@link CodeActionRequest}. ----@class lsp.CodeActionRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link WorkspaceSymbolRequest}. ----@class lsp.WorkspaceSymbolParams ----A query string to filter symbols by. Clients may send an empty ----string here to request all symbols. ----@field query string - ----A special workspace symbol that supports locations without a range. ---- ----See also SymbolInformation. ---- ----@since 3.17.0 ----@class lsp.WorkspaceSymbol: lsp.BaseSymbolInformation ----The location of the symbol. Whether a server is allowed to ----return a location without a range depends on the client ----capability `workspace.symbol.resolveSupport`. ---- ----See SymbolInformation#location for more details. ----@field location lsp.Location|anonym5 ----A data entry field that is preserved on a workspace symbol between a ----workspace symbol request and a workspace symbol resolve request. ----@field data? lsp.LSPAny - ----Registration options for a {@link WorkspaceSymbolRequest}. ----@class lsp.WorkspaceSymbolRegistrationOptions: lsp.WorkspaceSymbolOptions - ----The parameters of a {@link CodeLensRequest}. ----@class lsp.CodeLensParams ----The document to request code lens for. ----@field textDocument lsp.TextDocumentIdentifier - ----A code lens represents a {@link Command command} that should be shown along with ----source text, like the number of references, a way to run tests, etc. ---- ----A code lens is _unresolved_ when no command is associated to it. For performance ----reasons the creation of a code lens and resolving should be done in two stages. ----@class lsp.CodeLens ----The range in which this code lens is valid. Should only span a single line. ----@field range lsp.Range ----The command this code lens represents. ----@field command? lsp.Command ----A data entry field that is preserved on a code lens item between ----a {@link CodeLensRequest} and a [CodeLensResolveRequest] ----(#CodeLensResolveRequest) ----@field data? lsp.LSPAny - ----Registration options for a {@link CodeLensRequest}. ----@class lsp.CodeLensRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link DocumentLinkRequest}. ----@class lsp.DocumentLinkParams ----The document to provide document links for. ----@field textDocument lsp.TextDocumentIdentifier - ----A document link is a range in a text document that links to an internal or external resource, like another ----text document or a web site. ----@class lsp.DocumentLink ----The range this link applies to. ----@field range lsp.Range ----The uri this link points to. If missing a resolve request is sent later. ----@field target? lsp.URI ----The tooltip text when you hover over this link. ---- ----If a tooltip is provided, is will be displayed in a string that includes instructions on how to ----trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, ----user settings, and localization. ---- ----@since 3.15.0 ----@field tooltip? string ----A data entry field that is preserved on a document link between a ----DocumentLinkRequest and a DocumentLinkResolveRequest. ----@field data? lsp.LSPAny - ----Registration options for a {@link DocumentLinkRequest}. ----@class lsp.DocumentLinkRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link DocumentFormattingRequest}. ----@class lsp.DocumentFormattingParams ----The document to format. ----@field textDocument lsp.TextDocumentIdentifier ----The format options. ----@field options lsp.FormattingOptions - ----Registration options for a {@link DocumentFormattingRequest}. ----@class lsp.DocumentFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link DocumentRangeFormattingRequest}. ----@class lsp.DocumentRangeFormattingParams ----The document to format. ----@field textDocument lsp.TextDocumentIdentifier ----The range to format ----@field range lsp.Range ----The format options ----@field options lsp.FormattingOptions - ----Registration options for a {@link DocumentRangeFormattingRequest}. ----@class lsp.DocumentRangeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link DocumentRangesFormattingRequest}. ---- ----@since 3.18.0 ----@proposed ----@class lsp.DocumentRangesFormattingParams ----The document to format. ----@field textDocument lsp.TextDocumentIdentifier ----The ranges to format ----@field ranges lsp.Range[] ----The format options ----@field options lsp.FormattingOptions - ----The parameters of a {@link DocumentOnTypeFormattingRequest}. ----@class lsp.DocumentOnTypeFormattingParams ----The document to format. ----@field textDocument lsp.TextDocumentIdentifier ----The position around which the on type formatting should happen. ----This is not necessarily the exact position where the character denoted ----by the property `ch` got typed. ----@field position lsp.Position ----The character that has been typed that triggered the formatting ----on type request. That is not necessarily the last character that ----got inserted into the document since the client could auto insert ----characters as well (e.g. like automatic brace completion). ----@field ch string ----The formatting options. ----@field options lsp.FormattingOptions - ----Registration options for a {@link DocumentOnTypeFormattingRequest}. ----@class lsp.DocumentOnTypeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----The parameters of a {@link RenameRequest}. ----@class lsp.RenameParams ----The document to rename. ----@field textDocument lsp.TextDocumentIdentifier ----The position at which this request was sent. ----@field position lsp.Position ----The new name of the symbol. If the given name is not valid the ----request must return a {@link ResponseError} with an ----appropriate message set. ----@field newName string - ----Registration options for a {@link RenameRequest}. ----@class lsp.RenameRegistrationOptions: lsp.TextDocumentRegistrationOptions - ----@class lsp.PrepareRenameParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams - ----The parameters of a {@link ExecuteCommandRequest}. ----@class lsp.ExecuteCommandParams ----The identifier of the actual command handler. ----@field command string ----Arguments that the command should be invoked with. ----@field arguments? lsp.LSPAny[] - ----Registration options for a {@link ExecuteCommandRequest}. ----@class lsp.ExecuteCommandRegistrationOptions: lsp.ExecuteCommandOptions - ----The parameters passed via an apply workspace edit request. ----@class lsp.ApplyWorkspaceEditParams ----An optional label of the workspace edit. This label is ----presented in the user interface for example on an undo ----stack to undo the workspace edit. ----@field label? string ----The edits to apply. ----@field edit lsp.WorkspaceEdit - ----The result returned from the apply workspace edit request. ---- ----@since 3.17 renamed from ApplyWorkspaceEditResponse ----@class lsp.ApplyWorkspaceEditResult ----Indicates whether the edit was applied or not. ----@field applied boolean ----An optional textual description for why the edit was not applied. ----This may be used by the server for diagnostic logging or to provide ----a suitable error for a request that triggered the edit. ----@field failureReason? string ----Depending on the client's failure handling strategy `failedChange` might ----contain the index of the change that failed. This property is only available ----if the client signals a `failureHandlingStrategy` in its client capabilities. ----@field failedChange? uinteger - ----@class lsp.WorkDoneProgressBegin ----@field kind "begin" ----Mandatory title of the progress operation. Used to briefly inform about ----the kind of operation being performed. ---- ----Examples: "Indexing" or "Linking dependencies". ----@field title string ----Controls if a cancel button should show to allow the user to cancel the ----long running operation. Clients that don't support cancellation are allowed ----to ignore the setting. ----@field cancellable? boolean ----Optional, more detailed associated progress message. Contains ----complementary information to the `title`. ---- ----Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". ----If unset, the previous progress message (if any) is still valid. ----@field message? string ----Optional progress percentage to display (value 100 is considered 100%). ----If not provided infinite progress is assumed and clients are allowed ----to ignore the `percentage` value in subsequent in report notifications. ---- ----The value should be steadily rising. Clients are free to ignore values ----that are not following this rule. The value range is [0, 100]. ----@field percentage? uinteger - ----@class lsp.WorkDoneProgressReport ----@field kind "report" ----Controls enablement state of a cancel button. ---- ----Clients that don't support cancellation or don't support controlling the button's ----enablement state are allowed to ignore the property. ----@field cancellable? boolean ----Optional, more detailed associated progress message. Contains ----complementary information to the `title`. ---- ----Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". ----If unset, the previous progress message (if any) is still valid. ----@field message? string ----Optional progress percentage to display (value 100 is considered 100%). ----If not provided infinite progress is assumed and clients are allowed ----to ignore the `percentage` value in subsequent in report notifications. ---- ----The value should be steadily rising. Clients are free to ignore values ----that are not following this rule. The value range is [0, 100] ----@field percentage? uinteger - ----@class lsp.WorkDoneProgressEnd ----@field kind "end" ----Optional, a final message indicating to for example indicate the outcome ----of the operation. ----@field message? string - ----@class lsp.SetTraceParams ----@field value lsp.TraceValues - ----@class lsp.LogTraceParams ----@field message string ----@field verbose? string - ----@class lsp.CancelParams ----The request id to cancel. ----@field id integer|string - ----@class lsp.ProgressParams ----The progress token provided by the client or server. ----@field token lsp.ProgressToken ----The progress data. ----@field value lsp.LSPAny - ----A parameter literal used in requests to pass a text document and a position inside that ----document. ----@class lsp.TextDocumentPositionParams ----The text document. ----@field textDocument lsp.TextDocumentIdentifier ----The position inside the text document. ----@field position lsp.Position - ----@class lsp.WorkDoneProgressParams ----An optional token that a server can use to report work done progress. ----@field workDoneToken? lsp.ProgressToken - ----@class lsp.PartialResultParams ----An optional token that a server can use to report partial results (e.g. streaming) to ----the client. ----@field partialResultToken? lsp.ProgressToken - ----Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, ----including an origin range. ----@class lsp.LocationLink ----Span of the origin of this link. ---- ----Used as the underlined span for mouse interaction. Defaults to the word range at ----the definition position. ----@field originSelectionRange? lsp.Range ----The target resource identifier of this link. ----@field targetUri lsp.DocumentUri ----The full target range of this link. If the target for example is a symbol then target range is the ----range enclosing this symbol not including leading/trailing whitespace but everything else ----like comments. This information is typically used to highlight the range in the editor. ----@field targetRange lsp.Range ----The range that should be selected and revealed when this link is being followed, e.g the name of a function. ----Must be contained by the `targetRange`. See also `DocumentSymbol#range` ----@field targetSelectionRange lsp.Range - ----A range in a text document expressed as (zero-based) start and end positions. ---- ----If you want to specify a range that contains a line including the line ending ----character(s) then use an end position denoting the start of the next line. ----For example: ----```ts ----{ ---- start: { line: 5, character: 23 } ---- end : { line 6, character : 0 } ----} ----``` ----@class lsp.Range ----The range's start position. ----@field start lsp.Position ----The range's end position. ----@field end lsp.Position - ----@class lsp.ImplementationOptions - ----Static registration options to be returned in the initialize ----request. ----@class lsp.StaticRegistrationOptions ----The id used to register the request. The id can be used to deregister ----the request again. See also Registration#id. ----@field id? string - ----@class lsp.TypeDefinitionOptions - ----The workspace folder change event. ----@class lsp.WorkspaceFoldersChangeEvent ----The array of added workspace folders ----@field added lsp.WorkspaceFolder[] ----The array of the removed workspace folders ----@field removed lsp.WorkspaceFolder[] - ----@class lsp.ConfigurationItem ----The scope to get the configuration section for. ----@field scopeUri? string ----The configuration section asked for. ----@field section? string - ----A literal to identify a text document in the client. ----@class lsp.TextDocumentIdentifier ----The text document's uri. ----@field uri lsp.DocumentUri - ----Represents a color in RGBA space. ----@class lsp.Color ----The red component of this color in the range [0-1]. ----@field red decimal ----The green component of this color in the range [0-1]. ----@field green decimal ----The blue component of this color in the range [0-1]. ----@field blue decimal ----The alpha component of this color in the range [0-1]. ----@field alpha decimal - ----@class lsp.DocumentColorOptions - ----@class lsp.FoldingRangeOptions - ----@class lsp.DeclarationOptions - ----Position in a text document expressed as zero-based line and character ----offset. Prior to 3.17 the offsets were always based on a UTF-16 string ----representation. So a string of the form `a𐐀b` the character offset of the ----character `a` is 0, the character offset of `𐐀` is 1 and the character ----offset of b is 3 since `𐐀` is represented using two code units in UTF-16. ----Since 3.17 clients and servers can agree on a different string encoding ----representation (e.g. UTF-8). The client announces it's supported encoding ----via the client capability [`general.positionEncodings`](#clientCapabilities). ----The value is an array of position encodings the client supports, with ----decreasing preference (e.g. the encoding at index `0` is the most preferred ----one). To stay backwards compatible the only mandatory encoding is UTF-16 ----represented via the string `utf-16`. The server can pick one of the ----encodings offered by the client and signals that encoding back to the ----client via the initialize result's property ----[`capabilities.positionEncoding`](#serverCapabilities). If the string value ----`utf-16` is missing from the client's capability `general.positionEncodings` ----servers can safely assume that the client supports UTF-16. If the server ----omits the position encoding in its initialize result the encoding defaults ----to the string value `utf-16`. Implementation considerations: since the ----conversion from one encoding into another requires the content of the ----file / line the conversion is best done where the file is read which is ----usually on the server side. ---- ----Positions are line end character agnostic. So you can not specify a position ----that denotes `\r|\n` or `\n|` where `|` represents the character offset. ---- ----@since 3.17.0 - support for negotiated position encoding. ----@class lsp.Position ----Line position in a document (zero-based). ---- ----If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. ----If a line number is negative, it defaults to 0. ----@field line uinteger ----Character offset on a line in a document (zero-based). ---- ----The meaning of this offset is determined by the negotiated ----`PositionEncodingKind`. ---- ----If the character value is greater than the line length it defaults back to the ----line length. ----@field character uinteger - ----@class lsp.SelectionRangeOptions - ----Call hierarchy options used during static registration. ---- ----@since 3.16.0 ----@class lsp.CallHierarchyOptions - ----@since 3.16.0 ----@class lsp.SemanticTokensOptions ----The legend used by the server ----@field legend lsp.SemanticTokensLegend ----Server supports providing semantic tokens for a specific range ----of a document. ----@field range? boolean|anonym6 ----Server supports providing semantic tokens for a full document. ----@field full? boolean|anonym7 - ----@since 3.16.0 ----@class lsp.SemanticTokensEdit ----The start offset of the edit. ----@field start uinteger ----The count of elements to remove. ----@field deleteCount uinteger ----The elements to insert. ----@field data? uinteger[] - ----@class lsp.LinkedEditingRangeOptions - ----Represents information on a file/folder create. ---- ----@since 3.16.0 ----@class lsp.FileCreate ----A file:// URI for the location of the file/folder being created. ----@field uri string - ----Describes textual changes on a text document. A TextDocumentEdit describes all changes ----on a document version Si and after they are applied move the document to version Si+1. ----So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any ----kind of ordering. However the edits must be non overlapping. ----@class lsp.TextDocumentEdit ----The text document to change. ----@field textDocument lsp.OptionalVersionedTextDocumentIdentifier ----The edits to be applied. ---- ----@since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a ----client capability. ----@field edits lsp.TextEdit|lsp.AnnotatedTextEdit[] - ----Create file operation. ----@class lsp.CreateFile: lsp.ResourceOperation ----A create ----@field kind "create" ----The resource to create. ----@field uri lsp.DocumentUri ----Additional options ----@field options? lsp.CreateFileOptions - ----Rename file operation ----@class lsp.RenameFile: lsp.ResourceOperation ----A rename ----@field kind "rename" ----The old (existing) location. ----@field oldUri lsp.DocumentUri ----The new location. ----@field newUri lsp.DocumentUri ----Rename options. ----@field options? lsp.RenameFileOptions - ----Delete file operation ----@class lsp.DeleteFile: lsp.ResourceOperation ----A delete ----@field kind "delete" ----The file to delete. ----@field uri lsp.DocumentUri ----Delete options. ----@field options? lsp.DeleteFileOptions - ----Additional information that describes document changes. ---- ----@since 3.16.0 ----@class lsp.ChangeAnnotation ----A human-readable string describing the actual change. The string ----is rendered prominent in the user interface. ----@field label string ----A flag which indicates that user confirmation is needed ----before applying the change. ----@field needsConfirmation? boolean ----A human-readable string which is rendered less prominent in ----the user interface. ----@field description? string - ----A filter to describe in which file operation requests or notifications ----the server is interested in receiving. ---- ----@since 3.16.0 ----@class lsp.FileOperationFilter ----A Uri scheme like `file` or `untitled`. ----@field scheme? string ----The actual file operation pattern. ----@field pattern lsp.FileOperationPattern - ----Represents information on a file/folder rename. ---- ----@since 3.16.0 ----@class lsp.FileRename ----A file:// URI for the original location of the file/folder being renamed. ----@field oldUri string ----A file:// URI for the new location of the file/folder being renamed. ----@field newUri string - ----Represents information on a file/folder delete. ---- ----@since 3.16.0 ----@class lsp.FileDelete ----A file:// URI for the location of the file/folder being deleted. ----@field uri string - ----@class lsp.MonikerOptions - ----Type hierarchy options used during static registration. ---- ----@since 3.17.0 ----@class lsp.TypeHierarchyOptions - ----@since 3.17.0 ----@class lsp.InlineValueContext ----The stack frame (as a DAP Id) where the execution has stopped. ----@field frameId integer ----The document range where execution has stopped. ----Typically the end position of the range denotes the line where the inline values are shown. ----@field stoppedLocation lsp.Range - ----Provide inline value as text. ---- ----@since 3.17.0 ----@class lsp.InlineValueText ----The document range for which the inline value applies. ----@field range lsp.Range ----The text of the inline value. ----@field text string - ----Provide inline value through a variable lookup. ----If only a range is specified, the variable name will be extracted from the underlying document. ----An optional variable name can be used to override the extracted name. ---- ----@since 3.17.0 ----@class lsp.InlineValueVariableLookup ----The document range for which the inline value applies. ----The range is used to extract the variable name from the underlying document. ----@field range lsp.Range ----If specified the name of the variable to look up. ----@field variableName? string ----How to perform the lookup. ----@field caseSensitiveLookup boolean - ----Provide an inline value through an expression evaluation. ----If only a range is specified, the expression will be extracted from the underlying document. ----An optional expression can be used to override the extracted expression. ---- ----@since 3.17.0 ----@class lsp.InlineValueEvaluatableExpression ----The document range for which the inline value applies. ----The range is used to extract the evaluatable expression from the underlying document. ----@field range lsp.Range ----If specified the expression overrides the extracted expression. ----@field expression? string - ----Inline value options used during static registration. ---- ----@since 3.17.0 ----@class lsp.InlineValueOptions - ----An inlay hint label part allows for interactive and composite labels ----of inlay hints. ---- ----@since 3.17.0 ----@class lsp.InlayHintLabelPart ----The value of this label part. ----@field value string ----The tooltip text when you hover over this label part. Depending on ----the client capability `inlayHint.resolveSupport` clients might resolve ----this property late using the resolve request. ----@field tooltip? string|lsp.MarkupContent ----An optional source code location that represents this ----label part. ---- ----The editor will use this location for the hover and for code navigation ----features: This part will become a clickable link that resolves to the ----definition of the symbol at the given location (not necessarily the ----location itself), it shows the hover that shows at the given location, ----and it shows a context menu with further code navigation commands. ---- ----Depending on the client capability `inlayHint.resolveSupport` clients ----might resolve this property late using the resolve request. ----@field location? lsp.Location ----An optional command for this label part. ---- ----Depending on the client capability `inlayHint.resolveSupport` clients ----might resolve this property late using the resolve request. ----@field command? lsp.Command - ----A `MarkupContent` literal represents a string value which content is interpreted base on its ----kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. ---- ----If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. ----See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting ---- ----Here is an example how such a string can be constructed using JavaScript / TypeScript: ----```ts ----let markdown: MarkdownContent = { ---- kind: MarkupKind.Markdown, ---- value: [ ---- '# Header', ---- 'Some text', ---- '```typescript', ---- 'someCode();', ---- '```' ---- ].join('\n') ----}; ----``` ---- ----*Please Note* that clients might sanitize the return markdown. A client could decide to ----remove HTML from the markdown to avoid script execution. ----@class lsp.MarkupContent ----The type of the Markup ----@field kind lsp.MarkupKind ----The content itself ----@field value string - ----Inlay hint options used during static registration. ---- ----@since 3.17.0 ----@class lsp.InlayHintOptions ----The server provides support to resolve additional ----information for an inlay hint item. ----@field resolveProvider? boolean - ----A full diagnostic report with a set of related documents. ---- ----@since 3.17.0 ----@class lsp.RelatedFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport ----Diagnostics of related documents. This information is useful ----in programming languages where code in a file A can generate ----diagnostics in a file B which A depends on. An example of ----such a language is C/C++ where marco definitions in a file ----a.cpp and result in errors in a header file b.hpp. ---- ----@since 3.17.0 ----@field relatedDocuments? table - ----An unchanged diagnostic report with a set of related documents. ---- ----@since 3.17.0 ----@class lsp.RelatedUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport ----Diagnostics of related documents. This information is useful ----in programming languages where code in a file A can generate ----diagnostics in a file B which A depends on. An example of ----such a language is C/C++ where marco definitions in a file ----a.cpp and result in errors in a header file b.hpp. ---- ----@since 3.17.0 ----@field relatedDocuments? table - ----A diagnostic report with a full set of problems. ---- ----@since 3.17.0 ----@class lsp.FullDocumentDiagnosticReport ----A full document diagnostic report. ----@field kind "full" ----An optional result id. If provided it will ----be sent on the next diagnostic request for the ----same document. ----@field resultId? string ----The actual items. ----@field items lsp.Diagnostic[] - ----A diagnostic report indicating that the last returned ----report is still accurate. ---- ----@since 3.17.0 ----@class lsp.UnchangedDocumentDiagnosticReport ----A document diagnostic report indicating ----no changes to the last result. A server can ----only return `unchanged` if result ids are ----provided. ----@field kind "unchanged" ----A result id which will be sent on the next ----diagnostic request for the same document. ----@field resultId string - ----Diagnostic options. ---- ----@since 3.17.0 ----@class lsp.DiagnosticOptions ----An optional identifier under which the diagnostics are ----managed by the client. ----@field identifier? string ----Whether the language has inter file dependencies meaning that ----editing code in one file can result in a different diagnostic ----set in another file. Inter file dependencies are common for ----most programming languages and typically uncommon for linters. ----@field interFileDependencies boolean ----The server provides support for workspace diagnostics as well. ----@field workspaceDiagnostics boolean - ----A previous result id in a workspace pull request. ---- ----@since 3.17.0 ----@class lsp.PreviousResultId ----The URI for which the client knowns a ----result id. ----@field uri lsp.DocumentUri ----The value of the previous result id. ----@field value string - ----A notebook document. ---- ----@since 3.17.0 ----@class lsp.NotebookDocument ----The notebook document's uri. ----@field uri lsp.URI ----The type of the notebook. ----@field notebookType string ----The version number of this document (it will increase after each ----change, including undo/redo). ----@field version integer ----Additional metadata stored with the notebook ----document. ---- ----Note: should always be an object literal (e.g. LSPObject) ----@field metadata? lsp.LSPObject ----The cells of a notebook. ----@field cells lsp.NotebookCell[] - ----An item to transfer a text document from the client to the ----server. ----@class lsp.TextDocumentItem ----The text document's uri. ----@field uri lsp.DocumentUri ----The text document's language identifier. ----@field languageId string ----The version number of this document (it will increase after each ----change, including undo/redo). ----@field version integer ----The content of the opened text document. ----@field text string - ----A versioned notebook document identifier. ---- ----@since 3.17.0 ----@class lsp.VersionedNotebookDocumentIdentifier ----The version number of this notebook document. ----@field version integer ----The notebook document's uri. ----@field uri lsp.URI - ----A change event for a notebook document. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentChangeEvent ----The changed meta data if any. ---- ----Note: should always be an object literal (e.g. LSPObject) ----@field metadata? lsp.LSPObject ----Changes to cells ----@field cells? anonym10 - ----A literal to identify a notebook document in the client. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentIdentifier ----The notebook document's uri. ----@field uri lsp.URI - ----Provides information about the context in which an inline completion was requested. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionContext ----Describes how the inline completion was triggered. ----@field triggerKind lsp.InlineCompletionTriggerKind ----Provides information about the currently selected item in the autocomplete widget if it is visible. ----@field selectedCompletionInfo? lsp.SelectedCompletionInfo - ----Inline completion options used during static registration. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionOptions - ----General parameters to to register for an notification or to register a provider. ----@class lsp.Registration ----The id used to register the request. The id can be used to deregister ----the request again. ----@field id string ----The method / capability to register for. ----@field method string ----Options necessary for the registration. ----@field registerOptions? lsp.LSPAny - ----General parameters to unregister a request or notification. ----@class lsp.Unregistration ----The id used to unregister the request or notification. Usually an id ----provided during the register request. ----@field id string ----The method to unregister for. ----@field method string - ----The initialize parameters ----@class lsp._InitializeParams ----The process Id of the parent process that started ----the server. ---- ----Is `null` if the process has not been started by another process. ----If the parent process is not alive then the server should exit. ----@field processId integer|lsp.null ----Information about the client ---- ----@since 3.15.0 ----@field clientInfo? anonym11 ----The locale the client is currently showing the user interface ----in. This must not necessarily be the locale of the operating ----system. ---- ----Uses IETF language tags as the value's syntax ----(See https://en.wikipedia.org/wiki/IETF_language_tag) ---- ----@since 3.16.0 ----@field locale? string ----The rootPath of the workspace. Is null ----if no folder is open. ---- ----@deprecated in favour of rootUri. ----@field rootPath? string|lsp.null ----The rootUri of the workspace. Is null if no ----folder is open. If both `rootPath` and `rootUri` are set ----`rootUri` wins. ---- ----@deprecated in favour of workspaceFolders. ----@field rootUri lsp.DocumentUri|lsp.null ----The capabilities provided by the client (editor or tool) ----@field capabilities lsp.ClientCapabilities ----User provided initialization options. ----@field initializationOptions? lsp.LSPAny ----The initial trace setting. If omitted trace is disabled ('off'). ----@field trace? lsp.TraceValues - ----@class lsp.WorkspaceFoldersInitializeParams ----The workspace folders configured in the client when the server starts. ---- ----This property is only available if the client supports workspace folders. ----It can be `null` if the client supports workspace folders but none are ----configured. ---- ----@since 3.6.0 ----@field workspaceFolders? lsp.WorkspaceFolder[]|lsp.null - ----Defines the capabilities provided by a language ----server. ----@class lsp.ServerCapabilities ----The position encoding the server picked from the encodings offered ----by the client via the client capability `general.positionEncodings`. ---- ----If the client didn't provide any position encodings the only valid ----value that a server can return is 'utf-16'. ---- ----If omitted it defaults to 'utf-16'. ---- ----@since 3.17.0 ----@field positionEncoding? lsp.PositionEncodingKind ----Defines how text documents are synced. Is either a detailed structure ----defining each notification or for backwards compatibility the ----TextDocumentSyncKind number. ----@field textDocumentSync? lsp.TextDocumentSyncOptions|lsp.TextDocumentSyncKind ----Defines how notebook documents are synced. ---- ----@since 3.17.0 ----@field notebookDocumentSync? lsp.NotebookDocumentSyncOptions|lsp.NotebookDocumentSyncRegistrationOptions ----The server provides completion support. ----@field completionProvider? lsp.CompletionOptions ----The server provides hover support. ----@field hoverProvider? boolean|lsp.HoverOptions ----The server provides signature help support. ----@field signatureHelpProvider? lsp.SignatureHelpOptions ----The server provides Goto Declaration support. ----@field declarationProvider? boolean|lsp.DeclarationOptions|lsp.DeclarationRegistrationOptions ----The server provides goto definition support. ----@field definitionProvider? boolean|lsp.DefinitionOptions ----The server provides Goto Type Definition support. ----@field typeDefinitionProvider? boolean|lsp.TypeDefinitionOptions|lsp.TypeDefinitionRegistrationOptions ----The server provides Goto Implementation support. ----@field implementationProvider? boolean|lsp.ImplementationOptions|lsp.ImplementationRegistrationOptions ----The server provides find references support. ----@field referencesProvider? boolean|lsp.ReferenceOptions ----The server provides document highlight support. ----@field documentHighlightProvider? boolean|lsp.DocumentHighlightOptions ----The server provides document symbol support. ----@field documentSymbolProvider? boolean|lsp.DocumentSymbolOptions ----The server provides code actions. CodeActionOptions may only be ----specified if the client states that it supports ----`codeActionLiteralSupport` in its initial `initialize` request. ----@field codeActionProvider? boolean|lsp.CodeActionOptions ----The server provides code lens. ----@field codeLensProvider? lsp.CodeLensOptions ----The server provides document link support. ----@field documentLinkProvider? lsp.DocumentLinkOptions ----The server provides color provider support. ----@field colorProvider? boolean|lsp.DocumentColorOptions|lsp.DocumentColorRegistrationOptions ----The server provides workspace symbol support. ----@field workspaceSymbolProvider? boolean|lsp.WorkspaceSymbolOptions ----The server provides document formatting. ----@field documentFormattingProvider? boolean|lsp.DocumentFormattingOptions ----The server provides document range formatting. ----@field documentRangeFormattingProvider? boolean|lsp.DocumentRangeFormattingOptions ----The server provides document formatting on typing. ----@field documentOnTypeFormattingProvider? lsp.DocumentOnTypeFormattingOptions ----The server provides rename support. RenameOptions may only be ----specified if the client states that it supports ----`prepareSupport` in its initial `initialize` request. ----@field renameProvider? boolean|lsp.RenameOptions ----The server provides folding provider support. ----@field foldingRangeProvider? boolean|lsp.FoldingRangeOptions|lsp.FoldingRangeRegistrationOptions ----The server provides selection range support. ----@field selectionRangeProvider? boolean|lsp.SelectionRangeOptions|lsp.SelectionRangeRegistrationOptions ----The server provides execute command support. ----@field executeCommandProvider? lsp.ExecuteCommandOptions ----The server provides call hierarchy support. ---- ----@since 3.16.0 ----@field callHierarchyProvider? boolean|lsp.CallHierarchyOptions|lsp.CallHierarchyRegistrationOptions ----The server provides linked editing range support. ---- ----@since 3.16.0 ----@field linkedEditingRangeProvider? boolean|lsp.LinkedEditingRangeOptions|lsp.LinkedEditingRangeRegistrationOptions ----The server provides semantic tokens support. ---- ----@since 3.16.0 ----@field semanticTokensProvider? lsp.SemanticTokensOptions|lsp.SemanticTokensRegistrationOptions ----The server provides moniker support. ---- ----@since 3.16.0 ----@field monikerProvider? boolean|lsp.MonikerOptions|lsp.MonikerRegistrationOptions ----The server provides type hierarchy support. ---- ----@since 3.17.0 ----@field typeHierarchyProvider? boolean|lsp.TypeHierarchyOptions|lsp.TypeHierarchyRegistrationOptions ----The server provides inline values. ---- ----@since 3.17.0 ----@field inlineValueProvider? boolean|lsp.InlineValueOptions|lsp.InlineValueRegistrationOptions ----The server provides inlay hints. ---- ----@since 3.17.0 ----@field inlayHintProvider? boolean|lsp.InlayHintOptions|lsp.InlayHintRegistrationOptions ----The server has support for pull model diagnostics. ---- ----@since 3.17.0 ----@field diagnosticProvider? lsp.DiagnosticOptions|lsp.DiagnosticRegistrationOptions ----Inline completion options used during static registration. ---- ----@since 3.18.0 ----@field inlineCompletionProvider? boolean|lsp.InlineCompletionOptions ----Workspace specific server capabilities. ----@field workspace? anonym12 ----Experimental server capabilities. ----@field experimental? lsp.LSPAny - ----A text document identifier to denote a specific version of a text document. ----@class lsp.VersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier ----The version number of this document. ----@field version integer - ----Save options. ----@class lsp.SaveOptions ----The client is supposed to include the content on save. ----@field includeText? boolean - ----An event describing a file change. ----@class lsp.FileEvent ----The file's uri. ----@field uri lsp.DocumentUri ----The change type. ----@field type lsp.FileChangeType - ----@class lsp.FileSystemWatcher ----The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. ---- ----@since 3.17.0 support for relative patterns. ----@field globPattern lsp.GlobPattern ----The kind of events of interest. If omitted it defaults ----to WatchKind.Create | WatchKind.Change | WatchKind.Delete ----which is 7. ----@field kind? lsp.WatchKind - ----Represents a diagnostic, such as a compiler error or warning. Diagnostic objects ----are only valid in the scope of a resource. ----@class lsp.Diagnostic ----The range at which the message applies ----@field range lsp.Range ----The diagnostic's severity. Can be omitted. If omitted it is up to the ----client to interpret diagnostics as error, warning, info or hint. ----@field severity? lsp.DiagnosticSeverity ----The diagnostic's code, which usually appear in the user interface. ----@field code? integer|string ----An optional property to describe the error code. ----Requires the code field (above) to be present/not null. ---- ----@since 3.16.0 ----@field codeDescription? lsp.CodeDescription ----A human-readable string describing the source of this ----diagnostic, e.g. 'typescript' or 'super lint'. It usually ----appears in the user interface. ----@field source? string ----The diagnostic's message. It usually appears in the user interface ----@field message string ----Additional metadata about the diagnostic. ---- ----@since 3.15.0 ----@field tags? lsp.DiagnosticTag[] ----An array of related diagnostic information, e.g. when symbol-names within ----a scope collide all definitions can be marked via this property. ----@field relatedInformation? lsp.DiagnosticRelatedInformation[] ----A data entry field that is preserved between a `textDocument/publishDiagnostics` ----notification and `textDocument/codeAction` request. ---- ----@since 3.16.0 ----@field data? lsp.LSPAny - ----Contains additional information about the context in which a completion request is triggered. ----@class lsp.CompletionContext ----How the completion was triggered. ----@field triggerKind lsp.CompletionTriggerKind ----The trigger character (a single character) that has trigger code complete. ----Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` ----@field triggerCharacter? string - ----Additional details for a completion item label. ---- ----@since 3.17.0 ----@class lsp.CompletionItemLabelDetails ----An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, ----without any spacing. Should be used for function signatures and type annotations. ----@field detail? string ----An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used ----for fully qualified names and file paths. ----@field description? string - ----A special text edit to provide an insert and a replace operation. ---- ----@since 3.16.0 ----@class lsp.InsertReplaceEdit ----The string to be inserted. ----@field newText string ----The range if the insert is requested ----@field insert lsp.Range ----The range if the replace is requested. ----@field replace lsp.Range - ----Completion options. ----@class lsp.CompletionOptions ----Most tools trigger completion request automatically without explicitly requesting ----it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user ----starts to type an identifier. For example if the user types `c` in a JavaScript file ----code complete will automatically pop up present `console` besides others as a ----completion item. Characters that make up identifiers don't need to be listed here. ---- ----If code complete should automatically be trigger on characters not being valid inside ----an identifier (for example `.` in JavaScript) list them in `triggerCharacters`. ----@field triggerCharacters? string[] ----The list of all possible characters that commit a completion. This field can be used ----if clients don't support individual commit characters per completion item. See ----`ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` ---- ----If a server provides both `allCommitCharacters` and commit characters on an individual ----completion item the ones on the completion item win. ---- ----@since 3.2.0 ----@field allCommitCharacters? string[] ----The server provides support to resolve additional ----information for a completion item. ----@field resolveProvider? boolean ----The server supports the following `CompletionItem` specific ----capabilities. ---- ----@since 3.17.0 ----@field completionItem? anonym13 - ----Hover options. ----@class lsp.HoverOptions - ----Additional information about the context in which a signature help request was triggered. ---- ----@since 3.15.0 ----@class lsp.SignatureHelpContext ----Action that caused signature help to be triggered. ----@field triggerKind lsp.SignatureHelpTriggerKind ----Character that caused signature help to be triggered. ---- ----This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` ----@field triggerCharacter? string ----`true` if signature help was already showing when it was triggered. ---- ----Retriggers occurs when the signature help is already active and can be caused by actions such as ----typing a trigger character, a cursor move, or document content changes. ----@field isRetrigger boolean ----The currently active `SignatureHelp`. ---- ----The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on ----the user navigating through available signatures. ----@field activeSignatureHelp? lsp.SignatureHelp - ----Represents the signature of something callable. A signature ----can have a label, like a function-name, a doc-comment, and ----a set of parameters. ----@class lsp.SignatureInformation ----The label of this signature. Will be shown in ----the UI. ----@field label string ----The human-readable doc-comment of this signature. Will be shown ----in the UI but can be omitted. ----@field documentation? string|lsp.MarkupContent ----The parameters of this signature. ----@field parameters? lsp.ParameterInformation[] ----The index of the active parameter. ---- ----If provided, this is used in place of `SignatureHelp.activeParameter`. ---- ----@since 3.16.0 ----@field activeParameter? uinteger - ----Server Capabilities for a {@link SignatureHelpRequest}. ----@class lsp.SignatureHelpOptions ----List of characters that trigger signature help automatically. ----@field triggerCharacters? string[] ----List of characters that re-trigger signature help. ---- ----These trigger characters are only active when signature help is already showing. All trigger characters ----are also counted as re-trigger characters. ---- ----@since 3.15.0 ----@field retriggerCharacters? string[] - ----Server Capabilities for a {@link DefinitionRequest}. ----@class lsp.DefinitionOptions - ----Value-object that contains additional information when ----requesting references. ----@class lsp.ReferenceContext ----Include the declaration of the current symbol. ----@field includeDeclaration boolean - ----Reference options. ----@class lsp.ReferenceOptions - ----Provider options for a {@link DocumentHighlightRequest}. ----@class lsp.DocumentHighlightOptions - ----A base for all symbol information. ----@class lsp.BaseSymbolInformation ----The name of this symbol. ----@field name string ----The kind of this symbol. ----@field kind lsp.SymbolKind ----Tags for this symbol. ---- ----@since 3.16.0 ----@field tags? lsp.SymbolTag[] ----The name of the symbol containing this symbol. This information is for ----user interface purposes (e.g. to render a qualifier in the user interface ----if necessary). It can't be used to re-infer a hierarchy for the document ----symbols. ----@field containerName? string - ----Provider options for a {@link DocumentSymbolRequest}. ----@class lsp.DocumentSymbolOptions ----A human-readable string that is shown when multiple outlines trees ----are shown for the same document. ---- ----@since 3.16.0 ----@field label? string - ----Contains additional diagnostic information about the context in which ----a {@link CodeActionProvider.provideCodeActions code action} is run. ----@class lsp.CodeActionContext ----An array of diagnostics known on the client side overlapping the range provided to the ----`textDocument/codeAction` request. They are provided so that the server knows which ----errors are currently presented to the user for the given range. There is no guarantee ----that these accurately reflect the error state of the resource. The primary parameter ----to compute code actions is the provided range. ----@field diagnostics lsp.Diagnostic[] ----Requested kind of actions to return. ---- ----Actions not of this kind are filtered out by the client before being shown. So servers ----can omit computing them. ----@field only? lsp.CodeActionKind[] ----The reason why code actions were requested. ---- ----@since 3.17.0 ----@field triggerKind? lsp.CodeActionTriggerKind - ----Provider options for a {@link CodeActionRequest}. ----@class lsp.CodeActionOptions ----CodeActionKinds that this server may return. ---- ----The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server ----may list out every specific kind they provide. ----@field codeActionKinds? lsp.CodeActionKind[] ----The server provides support to resolve additional ----information for a code action. ---- ----@since 3.16.0 ----@field resolveProvider? boolean - ----Server capabilities for a {@link WorkspaceSymbolRequest}. ----@class lsp.WorkspaceSymbolOptions ----The server provides support to resolve additional ----information for a workspace symbol. ---- ----@since 3.17.0 ----@field resolveProvider? boolean - ----Code Lens provider options of a {@link CodeLensRequest}. ----@class lsp.CodeLensOptions ----Code lens has a resolve provider as well. ----@field resolveProvider? boolean - ----Provider options for a {@link DocumentLinkRequest}. ----@class lsp.DocumentLinkOptions ----Document links have a resolve provider as well. ----@field resolveProvider? boolean - ----Value-object describing what options formatting should use. ----@class lsp.FormattingOptions ----Size of a tab in spaces. ----@field tabSize uinteger ----Prefer spaces over tabs. ----@field insertSpaces boolean ----Trim trailing whitespace on a line. ---- ----@since 3.15.0 ----@field trimTrailingWhitespace? boolean ----Insert a newline character at the end of the file if one does not exist. ---- ----@since 3.15.0 ----@field insertFinalNewline? boolean ----Trim all newlines after the final newline at the end of the file. ---- ----@since 3.15.0 ----@field trimFinalNewlines? boolean - ----Provider options for a {@link DocumentFormattingRequest}. ----@class lsp.DocumentFormattingOptions - ----Provider options for a {@link DocumentRangeFormattingRequest}. ----@class lsp.DocumentRangeFormattingOptions ----Whether the server supports formatting multiple ranges at once. ---- ----@since 3.18.0 ----@proposed ----@field rangesSupport? boolean - ----Provider options for a {@link DocumentOnTypeFormattingRequest}. ----@class lsp.DocumentOnTypeFormattingOptions ----A character on which formatting should be triggered, like `{`. ----@field firstTriggerCharacter string ----More trigger characters. ----@field moreTriggerCharacter? string[] - ----Provider options for a {@link RenameRequest}. ----@class lsp.RenameOptions ----Renames should be checked and tested before being executed. ---- ----@since version 3.12.0 ----@field prepareProvider? boolean - ----The server capabilities of a {@link ExecuteCommandRequest}. ----@class lsp.ExecuteCommandOptions ----The commands to be executed on the server ----@field commands string[] - ----@since 3.16.0 ----@class lsp.SemanticTokensLegend ----The token types a server uses. ----@field tokenTypes string[] ----The token modifiers a server uses. ----@field tokenModifiers string[] - ----A text document identifier to optionally denote a specific version of a text document. ----@class lsp.OptionalVersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier ----The version number of this document. If a versioned text document identifier ----is sent from the server to the client and the file is not open in the editor ----(the server has not received an open notification before) the server can send ----`null` to indicate that the version is unknown and the content on disk is the ----truth (as specified with document content ownership). ----@field version integer|lsp.null - ----A special text edit with an additional change annotation. ---- ----@since 3.16.0. ----@class lsp.AnnotatedTextEdit: lsp.TextEdit ----The actual identifier of the change annotation ----@field annotationId lsp.ChangeAnnotationIdentifier - ----A generic resource operation. ----@class lsp.ResourceOperation ----The resource operation kind. ----@field kind string ----An optional annotation identifier describing the operation. ---- ----@since 3.16.0 ----@field annotationId? lsp.ChangeAnnotationIdentifier - ----Options to create a file. ----@class lsp.CreateFileOptions ----Overwrite existing file. Overwrite wins over `ignoreIfExists` ----@field overwrite? boolean ----Ignore if exists. ----@field ignoreIfExists? boolean - ----Rename file options ----@class lsp.RenameFileOptions ----Overwrite target if existing. Overwrite wins over `ignoreIfExists` ----@field overwrite? boolean ----Ignores if target exists. ----@field ignoreIfExists? boolean - ----Delete file options ----@class lsp.DeleteFileOptions ----Delete the content recursively if a folder is denoted. ----@field recursive? boolean ----Ignore the operation if the file doesn't exist. ----@field ignoreIfNotExists? boolean - ----A pattern to describe in which file operation requests or notifications ----the server is interested in receiving. ---- ----@since 3.16.0 ----@class lsp.FileOperationPattern ----The glob pattern to match. Glob patterns can have the following syntax: ----- `*` to match one or more characters in a path segment ----- `?` to match on one character in a path segment ----- `**` to match any number of path segments, including none ----- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) ----- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) ----- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) ----@field glob string ----Whether to match files or folders with this pattern. ---- ----Matches both if undefined. ----@field matches? lsp.FileOperationPatternKind ----Additional options used during matching. ----@field options? lsp.FileOperationPatternOptions - ----A full document diagnostic report for a workspace diagnostic result. ---- ----@since 3.17.0 ----@class lsp.WorkspaceFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport ----The URI for which diagnostic information is reported. ----@field uri lsp.DocumentUri ----The version number for which the diagnostics are reported. ----If the document is not marked as open `null` can be provided. ----@field version integer|lsp.null - ----An unchanged document diagnostic report for a workspace diagnostic result. ---- ----@since 3.17.0 ----@class lsp.WorkspaceUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport ----The URI for which diagnostic information is reported. ----@field uri lsp.DocumentUri ----The version number for which the diagnostics are reported. ----If the document is not marked as open `null` can be provided. ----@field version integer|lsp.null - ----A notebook cell. ---- ----A cell's document URI must be unique across ALL notebook ----cells and can therefore be used to uniquely identify a ----notebook cell or the cell's text document. ---- ----@since 3.17.0 ----@class lsp.NotebookCell ----The cell's kind ----@field kind lsp.NotebookCellKind ----The URI of the cell's text document ----content. ----@field document lsp.DocumentUri ----Additional metadata stored with the cell. ---- ----Note: should always be an object literal (e.g. LSPObject) ----@field metadata? lsp.LSPObject ----Additional execution summary information ----if supported by the client. ----@field executionSummary? lsp.ExecutionSummary - ----A change describing how to move a `NotebookCell` ----array from state S to S'. ---- ----@since 3.17.0 ----@class lsp.NotebookCellArrayChange ----The start oftest of the cell that changed. ----@field start uinteger ----The deleted cells ----@field deleteCount uinteger ----The new cells, if any ----@field cells? lsp.NotebookCell[] - ----Describes the currently selected completion item. ---- ----@since 3.18.0 ----@class lsp.SelectedCompletionInfo ----The range that will be replaced if this completion item is accepted. ----@field range lsp.Range ----The text the range will be replaced with if this completion is accepted. ----@field text string - ----Defines the capabilities provided by the client. ----@class lsp.ClientCapabilities ----Workspace specific client capabilities. ----@field workspace? lsp.WorkspaceClientCapabilities ----Text document specific client capabilities. ----@field textDocument? lsp.TextDocumentClientCapabilities ----Capabilities specific to the notebook document support. ---- ----@since 3.17.0 ----@field notebookDocument? lsp.NotebookDocumentClientCapabilities ----Window specific client capabilities. ----@field window? lsp.WindowClientCapabilities ----General client capabilities. ---- ----@since 3.16.0 ----@field general? lsp.GeneralClientCapabilities ----Experimental client capabilities. ----@field experimental? lsp.LSPAny - ----@class lsp.TextDocumentSyncOptions ----Open and close notifications are sent to the server. If omitted open close notification should not ----be sent. ----@field openClose? boolean ----Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full ----and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. ----@field change? lsp.TextDocumentSyncKind ----If present will save notifications are sent to the server. If omitted the notification should not be ----sent. ----@field willSave? boolean ----If present will save wait until requests are sent to the server. If omitted the request should not be ----sent. ----@field willSaveWaitUntil? boolean ----If present save notifications are sent to the server. If omitted the notification should not be ----sent. ----@field save? boolean|lsp.SaveOptions - ----Options specific to a notebook plus its cells ----to be synced to the server. ---- ----If a selector provides a notebook document ----filter but no cell selector all cells of a ----matching notebook document will be synced. ---- ----If a selector provides no notebook document ----filter but only a cell selector all notebook ----document that contain at least one matching ----cell will be synced. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentSyncOptions ----The notebooks to be synced ----@field notebookSelector anonym15|anonym17[] ----Whether save notification should be forwarded to ----the server. Will only be honored if mode === `notebook`. ----@field save? boolean - ----Registration options specific to a notebook. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentSyncRegistrationOptions: lsp.NotebookDocumentSyncOptions, lsp.StaticRegistrationOptions - ----@class lsp.WorkspaceFoldersServerCapabilities ----The server has support for workspace folders ----@field supported? boolean ----Whether the server wants to receive workspace folder ----change notifications. ---- ----If a string is provided the string is treated as an ID ----under which the notification is registered on the client ----side. The ID can be used to unregister for these events ----using the `client/unregisterCapability` request. ----@field changeNotifications? string|boolean - ----Options for notifications/requests for user operations on files. ---- ----@since 3.16.0 ----@class lsp.FileOperationOptions ----The server is interested in receiving didCreateFiles notifications. ----@field didCreate? lsp.FileOperationRegistrationOptions ----The server is interested in receiving willCreateFiles requests. ----@field willCreate? lsp.FileOperationRegistrationOptions ----The server is interested in receiving didRenameFiles notifications. ----@field didRename? lsp.FileOperationRegistrationOptions ----The server is interested in receiving willRenameFiles requests. ----@field willRename? lsp.FileOperationRegistrationOptions ----The server is interested in receiving didDeleteFiles file notifications. ----@field didDelete? lsp.FileOperationRegistrationOptions ----The server is interested in receiving willDeleteFiles file requests. ----@field willDelete? lsp.FileOperationRegistrationOptions - ----Structure to capture a description for an error code. ---- ----@since 3.16.0 ----@class lsp.CodeDescription ----An URI to open with more information about the diagnostic error. ----@field href lsp.URI - ----Represents a related message and source code location for a diagnostic. This should be ----used to point to code locations that cause or related to a diagnostics, e.g when duplicating ----a symbol in a scope. ----@class lsp.DiagnosticRelatedInformation ----The location of this related diagnostic information. ----@field location lsp.Location ----The message of this related diagnostic information. ----@field message string - ----Represents a parameter of a callable-signature. A parameter can ----have a label and a doc-comment. ----@class lsp.ParameterInformation ----The label of this parameter information. ---- ----Either a string or an inclusive start and exclusive end offsets within its containing ----signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 ----string representation as `Position` and `Range` does. ---- ----*Note*: a label of type string should be a substring of its containing signature label. ----Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. ----@field label string|{ [1]: uinteger, [2]: uinteger } ----The human-readable doc-comment of this parameter. Will be shown ----in the UI but can be omitted. ----@field documentation? string|lsp.MarkupContent - ----A notebook cell text document filter denotes a cell text ----document by different properties. ---- ----@since 3.17.0 ----@class lsp.NotebookCellTextDocumentFilter ----A filter that matches against the notebook ----containing the notebook cell. If a string ----value is provided it matches against the ----notebook type. '*' matches every notebook. ----@field notebook string|lsp.NotebookDocumentFilter ----A language id like `python`. ---- ----Will be matched against the language id of the ----notebook cell document. '*' matches every language. ----@field language? string - ----Matching options for the file operation pattern. ---- ----@since 3.16.0 ----@class lsp.FileOperationPatternOptions ----The pattern should be matched ignoring casing. ----@field ignoreCase? boolean - ----@class lsp.ExecutionSummary ----A strict monotonically increasing value ----indicating the execution order of a cell ----inside a notebook. ----@field executionOrder uinteger ----Whether the execution was successful or ----not if known by the client. ----@field success? boolean - ----Workspace specific client capabilities. ----@class lsp.WorkspaceClientCapabilities ----The client supports applying batch edits ----to the workspace by supporting the request ----'workspace/applyEdit' ----@field applyEdit? boolean ----Capabilities specific to `WorkspaceEdit`s. ----@field workspaceEdit? lsp.WorkspaceEditClientCapabilities ----Capabilities specific to the `workspace/didChangeConfiguration` notification. ----@field didChangeConfiguration? lsp.DidChangeConfigurationClientCapabilities ----Capabilities specific to the `workspace/didChangeWatchedFiles` notification. ----@field didChangeWatchedFiles? lsp.DidChangeWatchedFilesClientCapabilities ----Capabilities specific to the `workspace/symbol` request. ----@field symbol? lsp.WorkspaceSymbolClientCapabilities ----Capabilities specific to the `workspace/executeCommand` request. ----@field executeCommand? lsp.ExecuteCommandClientCapabilities ----The client has support for workspace folders. ---- ----@since 3.6.0 ----@field workspaceFolders? boolean ----The client supports `workspace/configuration` requests. ---- ----@since 3.6.0 ----@field configuration? boolean ----Capabilities specific to the semantic token requests scoped to the ----workspace. ---- ----@since 3.16.0. ----@field semanticTokens? lsp.SemanticTokensWorkspaceClientCapabilities ----Capabilities specific to the code lens requests scoped to the ----workspace. ---- ----@since 3.16.0. ----@field codeLens? lsp.CodeLensWorkspaceClientCapabilities ----The client has support for file notifications/requests for user operations on files. ---- ----Since 3.16.0 ----@field fileOperations? lsp.FileOperationClientCapabilities ----Capabilities specific to the inline values requests scoped to the ----workspace. ---- ----@since 3.17.0. ----@field inlineValue? lsp.InlineValueWorkspaceClientCapabilities ----Capabilities specific to the inlay hint requests scoped to the ----workspace. ---- ----@since 3.17.0. ----@field inlayHint? lsp.InlayHintWorkspaceClientCapabilities ----Capabilities specific to the diagnostic requests scoped to the ----workspace. ---- ----@since 3.17.0. ----@field diagnostics? lsp.DiagnosticWorkspaceClientCapabilities - ----Text document specific client capabilities. ----@class lsp.TextDocumentClientCapabilities ----Defines which synchronization capabilities the client supports. ----@field synchronization? lsp.TextDocumentSyncClientCapabilities ----Capabilities specific to the `textDocument/completion` request. ----@field completion? lsp.CompletionClientCapabilities ----Capabilities specific to the `textDocument/hover` request. ----@field hover? lsp.HoverClientCapabilities ----Capabilities specific to the `textDocument/signatureHelp` request. ----@field signatureHelp? lsp.SignatureHelpClientCapabilities ----Capabilities specific to the `textDocument/declaration` request. ---- ----@since 3.14.0 ----@field declaration? lsp.DeclarationClientCapabilities ----Capabilities specific to the `textDocument/definition` request. ----@field definition? lsp.DefinitionClientCapabilities ----Capabilities specific to the `textDocument/typeDefinition` request. ---- ----@since 3.6.0 ----@field typeDefinition? lsp.TypeDefinitionClientCapabilities ----Capabilities specific to the `textDocument/implementation` request. ---- ----@since 3.6.0 ----@field implementation? lsp.ImplementationClientCapabilities ----Capabilities specific to the `textDocument/references` request. ----@field references? lsp.ReferenceClientCapabilities ----Capabilities specific to the `textDocument/documentHighlight` request. ----@field documentHighlight? lsp.DocumentHighlightClientCapabilities ----Capabilities specific to the `textDocument/documentSymbol` request. ----@field documentSymbol? lsp.DocumentSymbolClientCapabilities ----Capabilities specific to the `textDocument/codeAction` request. ----@field codeAction? lsp.CodeActionClientCapabilities ----Capabilities specific to the `textDocument/codeLens` request. ----@field codeLens? lsp.CodeLensClientCapabilities ----Capabilities specific to the `textDocument/documentLink` request. ----@field documentLink? lsp.DocumentLinkClientCapabilities ----Capabilities specific to the `textDocument/documentColor` and the ----`textDocument/colorPresentation` request. ---- ----@since 3.6.0 ----@field colorProvider? lsp.DocumentColorClientCapabilities ----Capabilities specific to the `textDocument/formatting` request. ----@field formatting? lsp.DocumentFormattingClientCapabilities ----Capabilities specific to the `textDocument/rangeFormatting` request. ----@field rangeFormatting? lsp.DocumentRangeFormattingClientCapabilities ----Capabilities specific to the `textDocument/onTypeFormatting` request. ----@field onTypeFormatting? lsp.DocumentOnTypeFormattingClientCapabilities ----Capabilities specific to the `textDocument/rename` request. ----@field rename? lsp.RenameClientCapabilities ----Capabilities specific to the `textDocument/foldingRange` request. ---- ----@since 3.10.0 ----@field foldingRange? lsp.FoldingRangeClientCapabilities ----Capabilities specific to the `textDocument/selectionRange` request. ---- ----@since 3.15.0 ----@field selectionRange? lsp.SelectionRangeClientCapabilities ----Capabilities specific to the `textDocument/publishDiagnostics` notification. ----@field publishDiagnostics? lsp.PublishDiagnosticsClientCapabilities ----Capabilities specific to the various call hierarchy requests. ---- ----@since 3.16.0 ----@field callHierarchy? lsp.CallHierarchyClientCapabilities ----Capabilities specific to the various semantic token request. ---- ----@since 3.16.0 ----@field semanticTokens? lsp.SemanticTokensClientCapabilities ----Capabilities specific to the `textDocument/linkedEditingRange` request. ---- ----@since 3.16.0 ----@field linkedEditingRange? lsp.LinkedEditingRangeClientCapabilities ----Client capabilities specific to the `textDocument/moniker` request. ---- ----@since 3.16.0 ----@field moniker? lsp.MonikerClientCapabilities ----Capabilities specific to the various type hierarchy requests. ---- ----@since 3.17.0 ----@field typeHierarchy? lsp.TypeHierarchyClientCapabilities ----Capabilities specific to the `textDocument/inlineValue` request. ---- ----@since 3.17.0 ----@field inlineValue? lsp.InlineValueClientCapabilities ----Capabilities specific to the `textDocument/inlayHint` request. ---- ----@since 3.17.0 ----@field inlayHint? lsp.InlayHintClientCapabilities ----Capabilities specific to the diagnostic pull model. ---- ----@since 3.17.0 ----@field diagnostic? lsp.DiagnosticClientCapabilities ----Client capabilities specific to inline completions. ---- ----@since 3.18.0 ----@field inlineCompletion? lsp.InlineCompletionClientCapabilities - ----Capabilities specific to the notebook document support. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentClientCapabilities ----Capabilities specific to notebook document synchronization ---- ----@since 3.17.0 ----@field synchronization lsp.NotebookDocumentSyncClientCapabilities - ----@class lsp.WindowClientCapabilities ----It indicates whether the client supports server initiated ----progress using the `window/workDoneProgress/create` request. ---- ----The capability also controls Whether client supports handling ----of progress notifications. If set servers are allowed to report a ----`workDoneProgress` property in the request specific server ----capabilities. ---- ----@since 3.15.0 ----@field workDoneProgress? boolean ----Capabilities specific to the showMessage request. ---- ----@since 3.16.0 ----@field showMessage? lsp.ShowMessageRequestClientCapabilities ----Capabilities specific to the showDocument request. ---- ----@since 3.16.0 ----@field showDocument? lsp.ShowDocumentClientCapabilities - ----General client capabilities. ---- ----@since 3.16.0 ----@class lsp.GeneralClientCapabilities ----Client capability that signals how the client ----handles stale requests (e.g. a request ----for which the client will not process the response ----anymore since the information is outdated). ---- ----@since 3.17.0 ----@field staleRequestSupport? anonym18 ----Client capabilities specific to regular expressions. ---- ----@since 3.16.0 ----@field regularExpressions? lsp.RegularExpressionsClientCapabilities ----Client capabilities specific to the client's markdown parser. ---- ----@since 3.16.0 ----@field markdown? lsp.MarkdownClientCapabilities ----The position encodings supported by the client. Client and server ----have to agree on the same position encoding to ensure that offsets ----(e.g. character position in a line) are interpreted the same on both ----sides. ---- ----To keep the protocol backwards compatible the following applies: if ----the value 'utf-16' is missing from the array of position encodings ----servers can assume that the client supports UTF-16. UTF-16 is ----therefore a mandatory encoding. ---- ----If omitted it defaults to ['utf-16']. ---- ----Implementation considerations: since the conversion from one encoding ----into another requires the content of the file / line the conversion ----is best done where the file is read which is usually on the server ----side. ---- ----@since 3.17.0 ----@field positionEncodings? lsp.PositionEncodingKind[] - ----A relative pattern is a helper to construct glob patterns that are matched ----relatively to a base URI. The common value for a `baseUri` is a workspace ----folder root, but it can be another absolute URI as well. ---- ----@since 3.17.0 ----@class lsp.RelativePattern ----A workspace folder or a base URI to which this pattern will be matched ----against relatively. ----@field baseUri lsp.WorkspaceFolder|lsp.URI ----The actual glob pattern; ----@field pattern lsp.Pattern - ----@class lsp.WorkspaceEditClientCapabilities ----The client supports versioned document changes in `WorkspaceEdit`s ----@field documentChanges? boolean ----The resource operations the client supports. Clients should at least ----support 'create', 'rename' and 'delete' files and folders. ---- ----@since 3.13.0 ----@field resourceOperations? lsp.ResourceOperationKind[] ----The failure handling strategy of a client if applying the workspace edit ----fails. ---- ----@since 3.13.0 ----@field failureHandling? lsp.FailureHandlingKind ----Whether the client normalizes line endings to the client specific ----setting. ----If set to `true` the client will normalize line ending characters ----in a workspace edit to the client-specified new line ----character. ---- ----@since 3.16.0 ----@field normalizesLineEndings? boolean ----Whether the client in general supports change annotations on text edits, ----create file, rename file and delete file changes. ---- ----@since 3.16.0 ----@field changeAnnotationSupport? anonym19 - ----@class lsp.DidChangeConfigurationClientCapabilities ----Did change configuration notification supports dynamic registration. ----@field dynamicRegistration? boolean - ----@class lsp.DidChangeWatchedFilesClientCapabilities ----Did change watched files notification supports dynamic registration. Please note ----that the current protocol doesn't support static configuration for file changes ----from the server side. ----@field dynamicRegistration? boolean ----Whether the client has support for {@link RelativePattern relative pattern} ----or not. ---- ----@since 3.17.0 ----@field relativePatternSupport? boolean - ----Client capabilities for a {@link WorkspaceSymbolRequest}. ----@class lsp.WorkspaceSymbolClientCapabilities ----Symbol request supports dynamic registration. ----@field dynamicRegistration? boolean ----Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. ----@field symbolKind? anonym20 ----The client supports tags on `SymbolInformation`. ----Clients supporting tags have to handle unknown tags gracefully. ---- ----@since 3.16.0 ----@field tagSupport? anonym21 ----The client support partial workspace symbols. The client will send the ----request `workspaceSymbol/resolve` to the server to resolve additional ----properties. ---- ----@since 3.17.0 ----@field resolveSupport? anonym22 - ----The client capabilities of a {@link ExecuteCommandRequest}. ----@class lsp.ExecuteCommandClientCapabilities ----Execute command supports dynamic registration. ----@field dynamicRegistration? boolean - ----@since 3.16.0 ----@class lsp.SemanticTokensWorkspaceClientCapabilities ----Whether the client implementation supports a refresh request sent from ----the server to the client. ---- ----Note that this event is global and will force the client to refresh all ----semantic tokens currently shown. It should be used with absolute care ----and is useful for situation where a server for example detects a project ----wide change that requires such a calculation. ----@field refreshSupport? boolean - ----@since 3.16.0 ----@class lsp.CodeLensWorkspaceClientCapabilities ----Whether the client implementation supports a refresh request sent from the ----server to the client. ---- ----Note that this event is global and will force the client to refresh all ----code lenses currently shown. It should be used with absolute care and is ----useful for situation where a server for example detect a project wide ----change that requires such a calculation. ----@field refreshSupport? boolean - ----Capabilities relating to events from file operations by the user in the client. ---- ----These events do not come from the file system, they come from user operations ----like renaming a file in the UI. ---- ----@since 3.16.0 ----@class lsp.FileOperationClientCapabilities ----Whether the client supports dynamic registration for file requests/notifications. ----@field dynamicRegistration? boolean ----The client has support for sending didCreateFiles notifications. ----@field didCreate? boolean ----The client has support for sending willCreateFiles requests. ----@field willCreate? boolean ----The client has support for sending didRenameFiles notifications. ----@field didRename? boolean ----The client has support for sending willRenameFiles requests. ----@field willRename? boolean ----The client has support for sending didDeleteFiles notifications. ----@field didDelete? boolean ----The client has support for sending willDeleteFiles requests. ----@field willDelete? boolean - ----Client workspace capabilities specific to inline values. ---- ----@since 3.17.0 ----@class lsp.InlineValueWorkspaceClientCapabilities ----Whether the client implementation supports a refresh request sent from the ----server to the client. ---- ----Note that this event is global and will force the client to refresh all ----inline values currently shown. It should be used with absolute care and is ----useful for situation where a server for example detects a project wide ----change that requires such a calculation. ----@field refreshSupport? boolean - ----Client workspace capabilities specific to inlay hints. ---- ----@since 3.17.0 ----@class lsp.InlayHintWorkspaceClientCapabilities ----Whether the client implementation supports a refresh request sent from ----the server to the client. ---- ----Note that this event is global and will force the client to refresh all ----inlay hints currently shown. It should be used with absolute care and ----is useful for situation where a server for example detects a project wide ----change that requires such a calculation. ----@field refreshSupport? boolean - ----Workspace client capabilities specific to diagnostic pull requests. ---- ----@since 3.17.0 ----@class lsp.DiagnosticWorkspaceClientCapabilities ----Whether the client implementation supports a refresh request sent from ----the server to the client. ---- ----Note that this event is global and will force the client to refresh all ----pulled diagnostics currently shown. It should be used with absolute care and ----is useful for situation where a server for example detects a project wide ----change that requires such a calculation. ----@field refreshSupport? boolean - ----@class lsp.TextDocumentSyncClientCapabilities ----Whether text document synchronization supports dynamic registration. ----@field dynamicRegistration? boolean ----The client supports sending will save notifications. ----@field willSave? boolean ----The client supports sending a will save request and ----waits for a response providing text edits which will ----be applied to the document before it is saved. ----@field willSaveWaitUntil? boolean ----The client supports did save notifications. ----@field didSave? boolean - ----Completion client capabilities ----@class lsp.CompletionClientCapabilities ----Whether completion supports dynamic registration. ----@field dynamicRegistration? boolean ----The client supports the following `CompletionItem` specific ----capabilities. ----@field completionItem? anonym26 ----@field completionItemKind? anonym27 ----Defines how the client handles whitespace and indentation ----when accepting a completion item that uses multi line ----text in either `insertText` or `textEdit`. ---- ----@since 3.17.0 ----@field insertTextMode? lsp.InsertTextMode ----The client supports to send additional context information for a ----`textDocument/completion` request. ----@field contextSupport? boolean ----The client supports the following `CompletionList` specific ----capabilities. ---- ----@since 3.17.0 ----@field completionList? anonym28 - ----@class lsp.HoverClientCapabilities ----Whether hover supports dynamic registration. ----@field dynamicRegistration? boolean ----Client supports the following content formats for the content ----property. The order describes the preferred format of the client. ----@field contentFormat? lsp.MarkupKind[] - ----Client Capabilities for a {@link SignatureHelpRequest}. ----@class lsp.SignatureHelpClientCapabilities ----Whether signature help supports dynamic registration. ----@field dynamicRegistration? boolean ----The client supports the following `SignatureInformation` ----specific properties. ----@field signatureInformation? anonym30 ----The client supports to send additional context information for a ----`textDocument/signatureHelp` request. A client that opts into ----contextSupport will also support the `retriggerCharacters` on ----`SignatureHelpOptions`. ---- ----@since 3.15.0 ----@field contextSupport? boolean - ----@since 3.14.0 ----@class lsp.DeclarationClientCapabilities ----Whether declaration supports dynamic registration. If this is set to `true` ----the client supports the new `DeclarationRegistrationOptions` return value ----for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----The client supports additional metadata in the form of declaration links. ----@field linkSupport? boolean - ----Client Capabilities for a {@link DefinitionRequest}. ----@class lsp.DefinitionClientCapabilities ----Whether definition supports dynamic registration. ----@field dynamicRegistration? boolean ----The client supports additional metadata in the form of definition links. ---- ----@since 3.14.0 ----@field linkSupport? boolean - ----Since 3.6.0 ----@class lsp.TypeDefinitionClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `TypeDefinitionRegistrationOptions` return value ----for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----The client supports additional metadata in the form of definition links. ---- ----Since 3.14.0 ----@field linkSupport? boolean - ----@since 3.6.0 ----@class lsp.ImplementationClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `ImplementationRegistrationOptions` return value ----for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----The client supports additional metadata in the form of definition links. ---- ----@since 3.14.0 ----@field linkSupport? boolean - ----Client Capabilities for a {@link ReferencesRequest}. ----@class lsp.ReferenceClientCapabilities ----Whether references supports dynamic registration. ----@field dynamicRegistration? boolean - ----Client Capabilities for a {@link DocumentHighlightRequest}. ----@class lsp.DocumentHighlightClientCapabilities ----Whether document highlight supports dynamic registration. ----@field dynamicRegistration? boolean - ----Client Capabilities for a {@link DocumentSymbolRequest}. ----@class lsp.DocumentSymbolClientCapabilities ----Whether document symbol supports dynamic registration. ----@field dynamicRegistration? boolean ----Specific capabilities for the `SymbolKind` in the ----`textDocument/documentSymbol` request. ----@field symbolKind? anonym31 ----The client supports hierarchical document symbols. ----@field hierarchicalDocumentSymbolSupport? boolean ----The client supports tags on `SymbolInformation`. Tags are supported on ----`DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. ----Clients supporting tags have to handle unknown tags gracefully. ---- ----@since 3.16.0 ----@field tagSupport? anonym32 ----The client supports an additional label presented in the UI when ----registering a document symbol provider. ---- ----@since 3.16.0 ----@field labelSupport? boolean - ----The Client Capabilities of a {@link CodeActionRequest}. ----@class lsp.CodeActionClientCapabilities ----Whether code action supports dynamic registration. ----@field dynamicRegistration? boolean ----The client support code action literals of type `CodeAction` as a valid ----response of the `textDocument/codeAction` request. If the property is not ----set the request can only return `Command` literals. ---- ----@since 3.8.0 ----@field codeActionLiteralSupport? anonym34 ----Whether code action supports the `isPreferred` property. ---- ----@since 3.15.0 ----@field isPreferredSupport? boolean ----Whether code action supports the `disabled` property. ---- ----@since 3.16.0 ----@field disabledSupport? boolean ----Whether code action supports the `data` property which is ----preserved between a `textDocument/codeAction` and a ----`codeAction/resolve` request. ---- ----@since 3.16.0 ----@field dataSupport? boolean ----Whether the client supports resolving additional code action ----properties via a separate `codeAction/resolve` request. ---- ----@since 3.16.0 ----@field resolveSupport? anonym35 ----Whether the client honors the change annotations in ----text edits and resource operations returned via the ----`CodeAction#edit` property by for example presenting ----the workspace edit in the user interface and asking ----for confirmation. ---- ----@since 3.16.0 ----@field honorsChangeAnnotations? boolean - ----The client capabilities of a {@link CodeLensRequest}. ----@class lsp.CodeLensClientCapabilities ----Whether code lens supports dynamic registration. ----@field dynamicRegistration? boolean - ----The client capabilities of a {@link DocumentLinkRequest}. ----@class lsp.DocumentLinkClientCapabilities ----Whether document link supports dynamic registration. ----@field dynamicRegistration? boolean ----Whether the client supports the `tooltip` property on `DocumentLink`. ---- ----@since 3.15.0 ----@field tooltipSupport? boolean - ----@class lsp.DocumentColorClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `DocumentColorRegistrationOptions` return value ----for the corresponding server capability as well. ----@field dynamicRegistration? boolean - ----Client capabilities of a {@link DocumentFormattingRequest}. ----@class lsp.DocumentFormattingClientCapabilities ----Whether formatting supports dynamic registration. ----@field dynamicRegistration? boolean - ----Client capabilities of a {@link DocumentRangeFormattingRequest}. ----@class lsp.DocumentRangeFormattingClientCapabilities ----Whether range formatting supports dynamic registration. ----@field dynamicRegistration? boolean ----Whether the client supports formatting multiple ranges at once. ---- ----@since 3.18.0 ----@proposed ----@field rangesSupport? boolean - ----Client capabilities of a {@link DocumentOnTypeFormattingRequest}. ----@class lsp.DocumentOnTypeFormattingClientCapabilities ----Whether on type formatting supports dynamic registration. ----@field dynamicRegistration? boolean - ----@class lsp.RenameClientCapabilities ----Whether rename supports dynamic registration. ----@field dynamicRegistration? boolean ----Client supports testing for validity of rename operations ----before execution. ---- ----@since 3.12.0 ----@field prepareSupport? boolean ----Client supports the default behavior result. ---- ----The value indicates the default behavior used by the ----client. ---- ----@since 3.16.0 ----@field prepareSupportDefaultBehavior? lsp.PrepareSupportDefaultBehavior ----Whether the client honors the change annotations in ----text edits and resource operations returned via the ----rename request's workspace edit by for example presenting ----the workspace edit in the user interface and asking ----for confirmation. ---- ----@since 3.16.0 ----@field honorsChangeAnnotations? boolean - ----@class lsp.FoldingRangeClientCapabilities ----Whether implementation supports dynamic registration for folding range ----providers. If this is set to `true` the client supports the new ----`FoldingRangeRegistrationOptions` return value for the corresponding ----server capability as well. ----@field dynamicRegistration? boolean ----The maximum number of folding ranges that the client prefers to receive ----per document. The value serves as a hint, servers are free to follow the ----limit. ----@field rangeLimit? uinteger ----If set, the client signals that it only supports folding complete lines. ----If set, client will ignore specified `startCharacter` and `endCharacter` ----properties in a FoldingRange. ----@field lineFoldingOnly? boolean ----Specific options for the folding range kind. ---- ----@since 3.17.0 ----@field foldingRangeKind? anonym36 ----Specific options for the folding range. ---- ----@since 3.17.0 ----@field foldingRange? anonym37 - ----@class lsp.SelectionRangeClientCapabilities ----Whether implementation supports dynamic registration for selection range providers. If this is set to `true` ----the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server ----capability as well. ----@field dynamicRegistration? boolean - ----The publish diagnostic client capabilities. ----@class lsp.PublishDiagnosticsClientCapabilities ----Whether the clients accepts diagnostics with related information. ----@field relatedInformation? boolean ----Client supports the tag property to provide meta data about a diagnostic. ----Clients supporting tags have to handle unknown tags gracefully. ---- ----@since 3.15.0 ----@field tagSupport? anonym38 ----Whether the client interprets the version property of the ----`textDocument/publishDiagnostics` notification's parameter. ---- ----@since 3.15.0 ----@field versionSupport? boolean ----Client supports a codeDescription property ---- ----@since 3.16.0 ----@field codeDescriptionSupport? boolean ----Whether code action supports the `data` property which is ----preserved between a `textDocument/publishDiagnostics` and ----`textDocument/codeAction` request. ---- ----@since 3.16.0 ----@field dataSupport? boolean - ----@since 3.16.0 ----@class lsp.CallHierarchyClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean - ----@since 3.16.0 ----@class lsp.SemanticTokensClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----Which requests the client supports and might send to the server ----depending on the server's capability. Please note that clients might not ----show semantic tokens or degrade some of the user experience if a range ----or full request is advertised by the client but not provided by the ----server. If for example the client capability `requests.full` and ----`request.range` are both set to true but the server only provides a ----range provider the client might not render a minimap correctly or might ----even decide to not show any semantic tokens at all. ----@field requests anonym41 ----The token types that the client supports. ----@field tokenTypes string[] ----The token modifiers that the client supports. ----@field tokenModifiers string[] ----The token formats the clients supports. ----@field formats lsp.TokenFormat[] ----Whether the client supports tokens that can overlap each other. ----@field overlappingTokenSupport? boolean ----Whether the client supports tokens that can span multiple lines. ----@field multilineTokenSupport? boolean ----Whether the client allows the server to actively cancel a ----semantic token request, e.g. supports returning ----LSPErrorCodes.ServerCancelled. If a server does the client ----needs to retrigger the request. ---- ----@since 3.17.0 ----@field serverCancelSupport? boolean ----Whether the client uses semantic tokens to augment existing ----syntax tokens. If set to `true` client side created syntax ----tokens and semantic tokens are both used for colorization. If ----set to `false` the client only uses the returned semantic tokens ----for colorization. ---- ----If the value is `undefined` then the client behavior is not ----specified. ---- ----@since 3.17.0 ----@field augmentsSyntaxTokens? boolean - ----Client capabilities for the linked editing range request. ---- ----@since 3.16.0 ----@class lsp.LinkedEditingRangeClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean - ----Client capabilities specific to the moniker request. ---- ----@since 3.16.0 ----@class lsp.MonikerClientCapabilities ----Whether moniker supports dynamic registration. If this is set to `true` ----the client supports the new `MonikerRegistrationOptions` return value ----for the corresponding server capability as well. ----@field dynamicRegistration? boolean - ----@since 3.17.0 ----@class lsp.TypeHierarchyClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean - ----Client capabilities specific to inline values. ---- ----@since 3.17.0 ----@class lsp.InlineValueClientCapabilities ----Whether implementation supports dynamic registration for inline value providers. ----@field dynamicRegistration? boolean - ----Inlay hint client capabilities. ---- ----@since 3.17.0 ----@class lsp.InlayHintClientCapabilities ----Whether inlay hints support dynamic registration. ----@field dynamicRegistration? boolean ----Indicates which properties a client can resolve lazily on an inlay ----hint. ----@field resolveSupport? anonym42 - ----Client capabilities specific to diagnostic pull requests. ---- ----@since 3.17.0 ----@class lsp.DiagnosticClientCapabilities ----Whether implementation supports dynamic registration. If this is set to `true` ----the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----Whether the clients supports related documents for document diagnostic pulls. ----@field relatedDocumentSupport? boolean - ----Client capabilities specific to inline completions. ---- ----@since 3.18.0 ----@class lsp.InlineCompletionClientCapabilities ----Whether implementation supports dynamic registration for inline completion providers. ----@field dynamicRegistration? boolean - ----Notebook specific client capabilities. ---- ----@since 3.17.0 ----@class lsp.NotebookDocumentSyncClientCapabilities ----Whether implementation supports dynamic registration. If this is ----set to `true` the client supports the new ----`(TextDocumentRegistrationOptions & StaticRegistrationOptions)` ----return value for the corresponding server capability as well. ----@field dynamicRegistration? boolean ----The client supports sending execution summary data per cell. ----@field executionSummarySupport? boolean - ----Show message request client capabilities ----@class lsp.ShowMessageRequestClientCapabilities ----Capabilities specific to the `MessageActionItem` type. ----@field messageActionItem? anonym43 - ----Client capabilities for the showDocument request. ---- ----@since 3.16.0 ----@class lsp.ShowDocumentClientCapabilities ----The client has support for the showDocument ----request. ----@field support boolean - ----Client capabilities specific to regular expressions. ---- ----@since 3.16.0 ----@class lsp.RegularExpressionsClientCapabilities ----The engine's name. ----@field engine string ----The engine's version. ----@field version? string - ----Client capabilities specific to the used markdown parser. ---- ----@since 3.16.0 ----@class lsp.MarkdownClientCapabilities ----The name of the parser. ----@field parser string ----The version of the parser. ----@field version? string ----A list of HTML tags that the client allows / supports in ----Markdown. ---- ----@since 3.17.0 ----@field allowedTags? string[] - ----A set of predefined token types. This set is not fixed ----an clients can specify additional token types via the ----corresponding client capabilities. ---- ----@since 3.16.0 ----@alias lsp.SemanticTokenTypes ----| "namespace" # namespace ----| "type" # type ----| "class" # class ----| "enum" # enum ----| "interface" # interface ----| "struct" # struct ----| "typeParameter" # typeParameter ----| "parameter" # parameter ----| "variable" # variable ----| "property" # property ----| "enumMember" # enumMember ----| "event" # event ----| "function" # function ----| "method" # method ----| "macro" # macro ----| "keyword" # keyword ----| "modifier" # modifier ----| "comment" # comment ----| "string" # string ----| "number" # number ----| "regexp" # regexp ----| "operator" # operator ----| "decorator" # decorator - ----A set of predefined token modifiers. This set is not fixed ----an clients can specify additional token types via the ----corresponding client capabilities. ---- ----@since 3.16.0 ----@alias lsp.SemanticTokenModifiers ----| "declaration" # declaration ----| "definition" # definition ----| "readonly" # readonly ----| "static" # static ----| "deprecated" # deprecated ----| "abstract" # abstract ----| "async" # async ----| "modification" # modification ----| "documentation" # documentation ----| "defaultLibrary" # defaultLibrary - ----The document diagnostic report kinds. ---- ----@since 3.17.0 ----@alias lsp.DocumentDiagnosticReportKind ----| "full" # Full ----| "unchanged" # Unchanged - ----Predefined error codes. ----@alias lsp.ErrorCodes ----| -32700 # ParseError ----| -32600 # InvalidRequest ----| -32601 # MethodNotFound ----| -32602 # InvalidParams ----| -32603 # InternalError ----| -32002 # ServerNotInitialized ----| -32001 # UnknownErrorCode - ----@alias lsp.LSPErrorCodes ----| -32803 # RequestFailed ----| -32802 # ServerCancelled ----| -32801 # ContentModified ----| -32800 # RequestCancelled - ----A set of predefined range kinds. ----@alias lsp.FoldingRangeKind ----| "comment" # Comment ----| "imports" # Imports ----| "region" # Region - ----A symbol kind. ----@alias lsp.SymbolKind ----| 1 # File ----| 2 # Module ----| 3 # Namespace ----| 4 # Package ----| 5 # Class ----| 6 # Method ----| 7 # Property ----| 8 # Field ----| 9 # Constructor ----| 10 # Enum ----| 11 # Interface ----| 12 # Function ----| 13 # Variable ----| 14 # Constant ----| 15 # String ----| 16 # Number ----| 17 # Boolean ----| 18 # Array ----| 19 # Object ----| 20 # Key ----| 21 # Null ----| 22 # EnumMember ----| 23 # Struct ----| 24 # Event ----| 25 # Operator ----| 26 # TypeParameter - ----Symbol tags are extra annotations that tweak the rendering of a symbol. ---- ----@since 3.16 ----@alias lsp.SymbolTag ----| 1 # Deprecated - ----Moniker uniqueness level to define scope of the moniker. ---- ----@since 3.16.0 ----@alias lsp.UniquenessLevel ----| "document" # document ----| "project" # project ----| "group" # group ----| "scheme" # scheme ----| "global" # global - ----The moniker kind. ---- ----@since 3.16.0 ----@alias lsp.MonikerKind ----| "import" # import ----| "export" # export ----| "local" # local - ----Inlay hint kinds. ---- ----@since 3.17.0 ----@alias lsp.InlayHintKind ----| 1 # Type ----| 2 # Parameter - ----Defines whether the insert text in a completion item should be interpreted as ----plain text or a snippet. ----@alias lsp.InsertTextFormat ----| 1 # PlainText ----| 2 # Snippet - ----The message type ----@alias lsp.MessageType ----| 1 # Error ----| 2 # Warning ----| 3 # Info ----| 4 # Log - ----Defines how the host (editor) should sync ----document changes to the language server. ----@alias lsp.TextDocumentSyncKind ----| 0 # None ----| 1 # Full ----| 2 # Incremental - ----Represents reasons why a text document is saved. ----@alias lsp.TextDocumentSaveReason ----| 1 # Manual ----| 2 # AfterDelay ----| 3 # FocusOut - ----The kind of a completion entry. ----@alias lsp.CompletionItemKind ----| 1 # Text ----| 2 # Method ----| 3 # Function ----| 4 # Constructor ----| 5 # Field ----| 6 # Variable ----| 7 # Class ----| 8 # Interface ----| 9 # Module ----| 10 # Property ----| 11 # Unit ----| 12 # Value ----| 13 # Enum ----| 14 # Keyword ----| 15 # Snippet ----| 16 # Color ----| 17 # File ----| 18 # Reference ----| 19 # Folder ----| 20 # EnumMember ----| 21 # Constant ----| 22 # Struct ----| 23 # Event ----| 24 # Operator ----| 25 # TypeParameter - ----Completion item tags are extra annotations that tweak the rendering of a completion ----item. ---- ----@since 3.15.0 ----@alias lsp.CompletionItemTag ----| 1 # Deprecated - ----How whitespace and indentation is handled during completion ----item insertion. ---- ----@since 3.16.0 ----@alias lsp.InsertTextMode ----| 1 # asIs ----| 2 # adjustIndentation - ----A document highlight kind. ----@alias lsp.DocumentHighlightKind ----| 1 # Text ----| 2 # Read ----| 3 # Write - ----A set of predefined code action kinds ----@alias lsp.CodeActionKind ----| "" # Empty ----| "quickfix" # QuickFix ----| "refactor" # Refactor ----| "refactor.extract" # RefactorExtract ----| "refactor.inline" # RefactorInline ----| "refactor.rewrite" # RefactorRewrite ----| "source" # Source ----| "source.organizeImports" # SourceOrganizeImports ----| "source.fixAll" # SourceFixAll - ----@alias lsp.TraceValues ----| "off" # Off ----| "messages" # Messages ----| "verbose" # Verbose - ----Describes the content type that a client supports in various ----result literals like `Hover`, `ParameterInfo` or `CompletionItem`. ---- ----Please note that `MarkupKinds` must not start with a `$`. This kinds ----are reserved for internal usage. ----@alias lsp.MarkupKind ----| "plaintext" # PlainText ----| "markdown" # Markdown - ----Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. ---- ----@since 3.18.0 ----@alias lsp.InlineCompletionTriggerKind ----| 0 # Invoked ----| 1 # Automatic - ----A set of predefined position encoding kinds. ---- ----@since 3.17.0 ----@alias lsp.PositionEncodingKind ----| "utf-8" # UTF8 ----| "utf-16" # UTF16 ----| "utf-32" # UTF32 - ----The file event type ----@alias lsp.FileChangeType ----| 1 # Created ----| 2 # Changed ----| 3 # Deleted - ----@alias lsp.WatchKind ----| 1 # Create ----| 2 # Change ----| 4 # Delete - ----The diagnostic's severity. ----@alias lsp.DiagnosticSeverity ----| 1 # Error ----| 2 # Warning ----| 3 # Information ----| 4 # Hint - ----The diagnostic tags. ---- ----@since 3.15.0 ----@alias lsp.DiagnosticTag ----| 1 # Unnecessary ----| 2 # Deprecated - ----How a completion was triggered ----@alias lsp.CompletionTriggerKind ----| 1 # Invoked ----| 2 # TriggerCharacter ----| 3 # TriggerForIncompleteCompletions - ----How a signature help was triggered. ---- ----@since 3.15.0 ----@alias lsp.SignatureHelpTriggerKind ----| 1 # Invoked ----| 2 # TriggerCharacter ----| 3 # ContentChange - ----The reason why code actions were requested. ---- ----@since 3.17.0 ----@alias lsp.CodeActionTriggerKind ----| 1 # Invoked ----| 2 # Automatic - ----A pattern kind describing if a glob pattern matches a file a folder or ----both. ---- ----@since 3.16.0 ----@alias lsp.FileOperationPatternKind ----| "file" # file ----| "folder" # folder - ----A notebook cell kind. ---- ----@since 3.17.0 ----@alias lsp.NotebookCellKind ----| 1 # Markup ----| 2 # Code - ----@alias lsp.ResourceOperationKind ----| "create" # Create ----| "rename" # Rename ----| "delete" # Delete - ----@alias lsp.FailureHandlingKind ----| "abort" # Abort ----| "transactional" # Transactional ----| "textOnlyTransactional" # TextOnlyTransactional ----| "undo" # Undo - ----@alias lsp.PrepareSupportDefaultBehavior ----| 1 # Identifier - ----@alias lsp.TokenFormat ----| "relative" # Relative - ----The definition of a symbol represented as one or many {@link Location locations}. ----For most programming languages there is only one location at which a symbol is ----defined. ---- ----Servers should prefer returning `DefinitionLink` over `Definition` if supported ----by the client. ----@alias lsp.Definition lsp.Location|lsp.Location[] - ----Information about where a symbol is defined. ---- ----Provides additional metadata over normal {@link Location location} definitions, including the range of ----the defining symbol ----@alias lsp.DefinitionLink lsp.LocationLink - ----LSP arrays. ----@since 3.17.0 ----@alias lsp.LSPArray lsp.LSPAny[] - ----The LSP any type. ----Please note that strictly speaking a property with the value `undefined` ----can't be converted into JSON preserving the property name. However for ----convenience it is allowed and assumed that all these properties are ----optional as well. ----@since 3.17.0 ----@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|integer|uinteger|decimal|boolean|lsp.null - ----The declaration of a symbol representation as one or many {@link Location locations}. ----@alias lsp.Declaration lsp.Location|lsp.Location[] - ----Information about where a symbol is declared. ---- ----Provides additional metadata over normal {@link Location location} declarations, including the range of ----the declaring symbol. ---- ----Servers should prefer returning `DeclarationLink` over `Declaration` if supported ----by the client. ----@alias lsp.DeclarationLink lsp.LocationLink - ----Inline value information can be provided by different means: ----- directly as a text value (class InlineValueText). ----- as a name to use for a variable lookup (class InlineValueVariableLookup) ----- as an evaluatable expression (class InlineValueEvaluatableExpression) ----The InlineValue types combines all inline value types into one type. ---- ----@since 3.17.0 ----@alias lsp.InlineValue lsp.InlineValueText|lsp.InlineValueVariableLookup|lsp.InlineValueEvaluatableExpression - ----The result of a document diagnostic pull request. A report can ----either be a full report containing all diagnostics for the ----requested document or an unchanged report indicating that nothing ----has changed in terms of diagnostics in comparison to the last ----pull request. ---- ----@since 3.17.0 ----@alias lsp.DocumentDiagnosticReport lsp.RelatedFullDocumentDiagnosticReport|lsp.RelatedUnchangedDocumentDiagnosticReport - ----@alias lsp.PrepareRenameResult lsp.Range|anonym44|anonym45 - ----A document selector is the combination of one or many document filters. ---- ----@sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`; ---- ----The use of a string as a document filter is deprecated @since 3.16.0. ----@alias lsp.DocumentSelector lsp.DocumentFilter[] - ----@alias lsp.ProgressToken integer|string - ----An identifier to refer to a change annotation stored with a workspace edit. ----@alias lsp.ChangeAnnotationIdentifier string - ----A workspace diagnostic document report. ---- ----@since 3.17.0 ----@alias lsp.WorkspaceDocumentDiagnosticReport lsp.WorkspaceFullDocumentDiagnosticReport|lsp.WorkspaceUnchangedDocumentDiagnosticReport - ----An event describing a change to a text document. If only a text is provided ----it is considered to be the full content of the document. ----@alias lsp.TextDocumentContentChangeEvent anonym46|anonym47 - ----MarkedString can be used to render human readable text. It is either a markdown string ----or a code-block that provides a language and a code snippet. The language identifier ----is semantically equal to the optional language identifier in fenced code blocks in GitHub ----issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting ---- ----The pair of a language and a value is an equivalent to markdown: ----```${language} ----${value} ----``` ---- ----Note that markdown strings will be sanitized - that means html will be escaped. ----@deprecated use MarkupContent instead. ----@alias lsp.MarkedString string|anonym48 - ----A document filter describes a top level text document or ----a notebook cell document. ---- ----@since 3.17.0 - proposed support for NotebookCellTextDocumentFilter. ----@alias lsp.DocumentFilter lsp.TextDocumentFilter|lsp.NotebookCellTextDocumentFilter - ----LSP object definition. ----@since 3.17.0 ----@alias lsp.LSPObject table - ----The glob pattern. Either a string pattern or a relative pattern. ---- ----@since 3.17.0 ----@alias lsp.GlobPattern lsp.Pattern|lsp.RelativePattern - ----A document filter denotes a document by different properties like ----the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of ----its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}. ---- ----Glob patterns can have the following syntax: ----- `*` to match one or more characters in a path segment ----- `?` to match on one character in a path segment ----- `**` to match any number of path segments, including none ----- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) ----- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) ----- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) ---- ----@sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` ----@sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` ---- ----@since 3.17.0 ----@alias lsp.TextDocumentFilter anonym49|anonym50|anonym51 - ----A notebook document filter denotes a notebook document by ----different properties. The properties will be match ----against the notebook's URI (same as with documents) ---- ----@since 3.17.0 ----@alias lsp.NotebookDocumentFilter anonym52|anonym53|anonym54 - ----The glob pattern to watch relative to the base path. Glob patterns can have the following syntax: ----- `*` to match one or more characters in a path segment ----- `?` to match on one character in a path segment ----- `**` to match any number of path segments, including none ----- `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) ----- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) ----- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) ---- ----@since 3.17.0 ----@alias lsp.Pattern string - ----@class anonym1 ----The name of the server as defined by the server. ----@field name string ----The server's version as defined by the server. ----@field version? string - ----@class anonym3 ----@field insert lsp.Range ----@field replace lsp.Range - ----@class anonym2 ----A default commit character set. ---- ----@since 3.17.0 ----@field commitCharacters? string[] ----A default edit range. ---- ----@since 3.17.0 ----@field editRange? lsp.Range|anonym3 ----A default insert text format. ---- ----@since 3.17.0 ----@field insertTextFormat? lsp.InsertTextFormat ----A default insert text mode. ---- ----@since 3.17.0 ----@field insertTextMode? lsp.InsertTextMode ----A default data value. ---- ----@since 3.17.0 ----@field data? lsp.LSPAny - ----@class anonym4 ----Human readable description of why the code action is currently disabled. ---- ----This is displayed in the code actions UI. ----@field reason string - ----@class anonym5 ----@field uri lsp.DocumentUri - ----@class anonym6 - ----@class anonym7 ----The server supports deltas for full documents. ----@field delta? boolean - ----@class anonym9 ----The change to the cell array. ----@field array lsp.NotebookCellArrayChange ----Additional opened cell text documents. ----@field didOpen? lsp.TextDocumentItem[] ----Additional closed cell text documents. ----@field didClose? lsp.TextDocumentIdentifier[] - ----@class anonym10 ----@field document lsp.VersionedTextDocumentIdentifier ----@field changes lsp.TextDocumentContentChangeEvent[] - ----@class anonym8 ----Changes to the cell structure to add or ----remove cells. ----@field structure? anonym9 ----Changes to notebook cells properties like its ----kind, execution summary or metadata. ----@field data? lsp.NotebookCell[] ----Changes to the text content of notebook cells. ----@field textContent? anonym10[] - ----@class anonym11 ----The name of the client as defined by the client. ----@field name string ----The client's version as defined by the client. ----@field version? string - ----@class anonym12 ----The server supports workspace folder. ---- ----@since 3.6.0 ----@field workspaceFolders? lsp.WorkspaceFoldersServerCapabilities ----The server is interested in notifications/requests for operations on files. ---- ----@since 3.16.0 ----@field fileOperations? lsp.FileOperationOptions - ----@class anonym13 ----The server has support for completion item label ----details (see also `CompletionItemLabelDetails`) when ----receiving a completion item in a resolve call. ---- ----@since 3.17.0 ----@field labelDetailsSupport? boolean - ----@class anonym15 ----@field language string - ----@class anonym14 ----The notebook to be synced If a string ----value is provided it matches against the ----notebook type. '*' matches every notebook. ----@field notebook string|lsp.NotebookDocumentFilter ----The cells of the matching notebook to be synced. ----@field cells? anonym15[] - ----@class anonym17 ----@field language string - ----@class anonym16 ----The notebook to be synced If a string ----value is provided it matches against the ----notebook type. '*' matches every notebook. ----@field notebook? string|lsp.NotebookDocumentFilter ----The cells of the matching notebook to be synced. ----@field cells anonym17[] - ----@class anonym18 ----The client will actively cancel the request. ----@field cancel boolean ----The list of requests for which the client ----will retry the request if it receives a ----response with error code `ContentModified` ----@field retryOnContentModified string[] - ----@class anonym19 ----Whether the client groups edits with equal labels into tree nodes, ----for instance all edits labelled with "Changes in Strings" would ----be a tree node. ----@field groupsOnLabel? boolean - ----@class anonym20 ----The symbol kind values the client supports. When this ----property exists the client also guarantees that it will ----handle values outside its set gracefully and falls back ----to a default value when unknown. ---- ----If this property is not present the client only supports ----the symbol kinds from `File` to `Array` as defined in ----the initial version of the protocol. ----@field valueSet? lsp.SymbolKind[] - ----@class anonym21 ----The tags supported by the client. ----@field valueSet lsp.SymbolTag[] - ----@class anonym22 ----The properties that a client can resolve lazily. Usually ----`location.range` ----@field properties string[] - ----@class anonym24 ----The tags supported by the client. ----@field valueSet lsp.CompletionItemTag[] - ----@class anonym25 ----The properties that a client can resolve lazily. ----@field properties string[] - ----@class anonym26 ----@field valueSet lsp.InsertTextMode[] - ----@class anonym23 ----Client supports snippets as insert text. ---- ----A snippet can define tab stops and placeholders with `$1`, `$2` ----and `${3:foo}`. `$0` defines the final tab stop, it defaults to ----the end of the snippet. Placeholders with equal identifiers are linked, ----that is typing in one will update others too. ----@field snippetSupport? boolean ----Client supports commit characters on a completion item. ----@field commitCharactersSupport? boolean ----Client supports the following content formats for the documentation ----property. The order describes the preferred format of the client. ----@field documentationFormat? lsp.MarkupKind[] ----Client supports the deprecated property on a completion item. ----@field deprecatedSupport? boolean ----Client supports the preselect property on a completion item. ----@field preselectSupport? boolean ----Client supports the tag property on a completion item. Clients supporting ----tags have to handle unknown tags gracefully. Clients especially need to ----preserve unknown tags when sending a completion item back to the server in ----a resolve call. ---- ----@since 3.15.0 ----@field tagSupport? anonym24 ----Client support insert replace edit to control different behavior if a ----completion item is inserted in the text or should replace text. ---- ----@since 3.16.0 ----@field insertReplaceSupport? boolean ----Indicates which properties a client can resolve lazily on a completion ----item. Before version 3.16.0 only the predefined properties `documentation` ----and `details` could be resolved lazily. ---- ----@since 3.16.0 ----@field resolveSupport? anonym25 ----The client supports the `insertTextMode` property on ----a completion item to override the whitespace handling mode ----as defined by the client (see `insertTextMode`). ---- ----@since 3.16.0 ----@field insertTextModeSupport? anonym26 ----The client has support for completion item label ----details (see also `CompletionItemLabelDetails`). ---- ----@since 3.17.0 ----@field labelDetailsSupport? boolean - ----@class anonym27 ----The completion item kind values the client supports. When this ----property exists the client also guarantees that it will ----handle values outside its set gracefully and falls back ----to a default value when unknown. ---- ----If this property is not present the client only supports ----the completion items kinds from `Text` to `Reference` as defined in ----the initial version of the protocol. ----@field valueSet? lsp.CompletionItemKind[] - ----@class anonym28 ----The client supports the following itemDefaults on ----a completion list. ---- ----The value lists the supported property names of the ----`CompletionList.itemDefaults` object. If omitted ----no properties are supported. ---- ----@since 3.17.0 ----@field itemDefaults? string[] - ----@class anonym30 ----The client supports processing label offsets instead of a ----simple label string. ---- ----@since 3.14.0 ----@field labelOffsetSupport? boolean - ----@class anonym29 ----Client supports the following content formats for the documentation ----property. The order describes the preferred format of the client. ----@field documentationFormat? lsp.MarkupKind[] ----Client capabilities specific to parameter information. ----@field parameterInformation? anonym30 ----The client supports the `activeParameter` property on `SignatureInformation` ----literal. ---- ----@since 3.16.0 ----@field activeParameterSupport? boolean - ----@class anonym31 ----The symbol kind values the client supports. When this ----property exists the client also guarantees that it will ----handle values outside its set gracefully and falls back ----to a default value when unknown. ---- ----If this property is not present the client only supports ----the symbol kinds from `File` to `Array` as defined in ----the initial version of the protocol. ----@field valueSet? lsp.SymbolKind[] - ----@class anonym32 ----The tags supported by the client. ----@field valueSet lsp.SymbolTag[] - ----@class anonym34 ----The code action kind values the client supports. When this ----property exists the client also guarantees that it will ----handle values outside its set gracefully and falls back ----to a default value when unknown. ----@field valueSet lsp.CodeActionKind[] - ----@class anonym33 ----The code action kind is support with the following value ----set. ----@field codeActionKind anonym34 - ----@class anonym35 ----The properties that a client can resolve lazily. ----@field properties string[] - ----@class anonym36 ----The folding range kind values the client supports. When this ----property exists the client also guarantees that it will ----handle values outside its set gracefully and falls back ----to a default value when unknown. ----@field valueSet? lsp.FoldingRangeKind[] - ----@class anonym37 ----If set, the client signals that it supports setting collapsedText on ----folding ranges to display custom labels instead of the default text. ---- ----@since 3.17.0 ----@field collapsedText? boolean - ----@class anonym38 ----The tags supported by the client. ----@field valueSet lsp.DiagnosticTag[] - ----@class anonym40 - ----@class anonym41 ----The client will send the `textDocument/semanticTokens/full/delta` request if ----the server provides a corresponding handler. ----@field delta? boolean - ----@class anonym39 ----The client will send the `textDocument/semanticTokens/range` request if ----the server provides a corresponding handler. ----@field range? boolean|anonym40 ----The client will send the `textDocument/semanticTokens/full` request if ----the server provides a corresponding handler. ----@field full? boolean|anonym41 - ----@class anonym42 ----The properties that a client can resolve lazily. ----@field properties string[] - ----@class anonym43 ----Whether the client supports additional attributes which ----are preserved and send back to the server in the ----request's response. ----@field additionalPropertiesSupport? boolean - ----@class anonym44 ----@field range lsp.Range ----@field placeholder string - ----@class anonym45 ----@field defaultBehavior boolean - ----@class anonym46 ----The range of the document that changed. ----@field range lsp.Range ----The optional length of the range that got replaced. ---- ----@deprecated use range instead. ----@field rangeLength? uinteger ----The new text for the provided range. ----@field text string - ----@class anonym47 ----The new text of the whole document. ----@field text string - ----@class anonym48 ----@field language string ----@field value string - ----@class anonym49 ----A language id, like `typescript`. ----@field language string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme? string ----A glob pattern, like `*.{ts,js}`. ----@field pattern? string - ----@class anonym50 ----A language id, like `typescript`. ----@field language? string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme string ----A glob pattern, like `*.{ts,js}`. ----@field pattern? string - ----@class anonym51 ----A language id, like `typescript`. ----@field language? string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme? string ----A glob pattern, like `*.{ts,js}`. ----@field pattern string - ----@class anonym52 ----The type of the enclosing notebook. ----@field notebookType string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme? string ----A glob pattern. ----@field pattern? string - ----@class anonym53 ----The type of the enclosing notebook. ----@field notebookType? string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme string ----A glob pattern. ----@field pattern? string - ----@class anonym54 ----The type of the enclosing notebook. ----@field notebookType? string ----A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. ----@field scheme? string ----A glob pattern. ----@field pattern string diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 738e23ff28..633cddca2d 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -715,8 +715,8 @@ end --- Turns the result of a `textDocument/completion` request into vim-compatible --- |complete-items|. --- ----@param result table The result of a `textDocument/completion` call, e.g. from ----|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, +---@param result table The result of a `textDocument/completion` call, e.g. +--- from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, --- `CompletionList` or `null` ---@param prefix (string) the prefix to filter the completion items ---@return table { matches = complete-items table, incomplete = bool } -- cgit From c235959fd909d75248c066a781475e207606c5aa Mon Sep 17 00:00:00 2001 From: Chris AtLee Date: Thu, 31 Aug 2023 04:00:24 -0400 Subject: fix(lsp): only disable inlay hints / diagnostics if no other clients are connected (#24535) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This fixes the issue where the LspNotify handlers for inlay_hint / diagnostics would end up refreshing all attached clients. The handler would call util._refresh, which called vim.lsp.buf_request, which calls the method on all attached clients. Now util._refresh takes an optional client_id parameter, which is used to specify a specific client to update. This commit also fixes util._refresh's handling of the `only_visible` flag. Previously if `only_visible` was false, two requests would be made to the server: one for the visible region, and one for the entire file. Co-authored-by: Stanislav Asunkin <1353637+stasjok@users.noreply.github.com> Co-authored-by: Mathias Fußenegger --- runtime/lua/vim/lsp/diagnostic.lua | 26 ++++++++++++++++--- runtime/lua/vim/lsp/inlay_hint.lua | 30 ++++++++++++++++----- runtime/lua/vim/lsp/util.lua | 53 +++++++++++++++++++++++++------------- 3 files changed, 81 insertions(+), 28 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index a0568bc09c..2a77992c4d 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -408,6 +408,16 @@ local function disable(bufnr) clear(bufnr) end +--- Refresh diagnostics, only if we have attached clients that support it +---@param bufnr (integer) buffer number +---@param opts? table Additional options to pass to util._refresh +---@private +local function _refresh(bufnr, opts) + opts = opts or {} + opts['bufnr'] = bufnr + util._refresh(ms.textDocument_diagnostic, opts) +end + --- Enable pull diagnostics for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current ---@private @@ -429,7 +439,7 @@ function M._enable(bufnr) return end if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh(ms.textDocument_diagnostic, { bufnr = bufnr, only_visible = true }) + _refresh(bufnr, { only_visible = true, client_id = opts.data.client_id }) end end, group = augroup, @@ -438,7 +448,7 @@ function M._enable(bufnr) api.nvim_buf_attach(bufnr, false, { on_reload = function() if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh(ms.textDocument_diagnostic, { bufnr = bufnr }) + _refresh(bufnr) end end, on_detach = function() @@ -448,8 +458,16 @@ function M._enable(bufnr) api.nvim_create_autocmd('LspDetach', { buffer = bufnr, - callback = function() - disable(bufnr) + callback = function(args) + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_diagnostic }) + + if + not vim.iter(clients):any(function(c) + return c.id ~= args.data.client_id + end) + then + disable(bufnr) + end end, group = augroup, }) diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 8407105d47..7b58188c53 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -131,6 +131,16 @@ local function disable(bufnr) end end +--- Refresh inlay hints, only if we have attached clients that support it +---@param bufnr (integer) Buffer handle, or 0 for current +---@param opts? table Additional options to pass to util._refresh +---@private +local function _refresh(bufnr, opts) + opts = opts or {} + opts['bufnr'] = bufnr + util._refresh(ms.textDocument_inlayHint, opts) +end + --- Enable inlay hints for a buffer ---@param bufnr (integer) Buffer handle, or 0 for current local function enable(bufnr) @@ -150,18 +160,18 @@ local function enable(bufnr) return end if bufstates[bufnr] and bufstates[bufnr].enabled then - util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) + _refresh(bufnr, { client_id = opts.data.client_id }) end end, group = augroup, }) - util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) + _refresh(bufnr) api.nvim_buf_attach(bufnr, false, { on_reload = function(_, cb_bufnr) clear(cb_bufnr) if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then bufstates[cb_bufnr].applied = {} - util._refresh(ms.textDocument_inlayHint, { bufnr = cb_bufnr }) + _refresh(cb_bufnr) end end, on_detach = function(_, cb_bufnr) @@ -170,14 +180,22 @@ local function enable(bufnr) }) api.nvim_create_autocmd('LspDetach', { buffer = bufnr, - callback = function() - disable(bufnr) + callback = function(args) + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_inlayHint }) + + if + not vim.iter(clients):any(function(c) + return c.id ~= args.data.client_id + end) + then + disable(bufnr) + end end, group = augroup, }) else bufstate.enabled = true - util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) + _refresh(bufnr) end end diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 633cddca2d..2e376f9093 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2122,6 +2122,7 @@ end function M.make_workspace_params(added, removed) return { event = { added = added, removed = removed } } end + --- Returns indentation size. --- ---@see 'shiftwidth' @@ -2192,32 +2193,46 @@ end ---@private --- Request updated LSP information for a buffer. --- +---@class lsp.util.RefreshOptions +---@field bufnr integer? Buffer to refresh (default: 0) +---@field only_visible? boolean Whether to only refresh for the visible regions of the buffer (default: false) +---@field client_id? integer Client ID to refresh (default: all clients) +-- ---@param method string LSP method to call ----@param opts (nil|table) Optional arguments ---- - bufnr (integer, default: 0): Buffer to refresh ---- - only_visible (boolean, default: false): Whether to only refresh for the visible regions of the buffer +---@param opts? lsp.util.RefreshOptions Options table function M._refresh(method, opts) opts = opts or {} local bufnr = opts.bufnr if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() end + + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = method, id = opts.client_id }) + + if #clients == 0 then + return + end + local only_visible = opts.only_visible or false - for _, window in ipairs(api.nvim_list_wins()) do - if api.nvim_win_get_buf(window) == bufnr then - local first = vim.fn.line('w0', window) - local last = vim.fn.line('w$', window) - local params = { - textDocument = M.make_text_document_params(bufnr), - range = { - start = { line = first - 1, character = 0 }, - ['end'] = { line = last, character = 0 }, - }, - } - vim.lsp.buf_request(bufnr, method, params) + + if only_visible then + for _, window in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(window) == bufnr then + local first = vim.fn.line('w0', window) + local last = vim.fn.line('w$', window) + local params = { + textDocument = M.make_text_document_params(bufnr), + range = { + start = { line = first - 1, character = 0 }, + ['end'] = { line = last, character = 0 }, + }, + } + for _, client in ipairs(clients) do + client.request(method, params, nil, bufnr) + end + end end - end - if not only_visible then + else local params = { textDocument = M.make_text_document_params(bufnr), range = { @@ -2225,7 +2240,9 @@ function M._refresh(method, opts) ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, }, } - vim.lsp.buf_request(bufnr, method, params) + for _, client in ipairs(clients) do + client.request(method, params, nil, bufnr) + end end end -- cgit From 597355deae2ebddcb8b930da9a8b45a65d05d09b Mon Sep 17 00:00:00 2001 From: TheBlob42 Date: Fri, 1 Sep 2023 13:31:05 +0200 Subject: fix(lsp): wrong iterator in registerCapability handler (#24971) --- runtime/lua/vim/lsp/handlers.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 6fe4b7f939..a6b70ac911 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -112,7 +112,7 @@ M[ms.client_registerCapability] = function(_, result, ctx) local client = vim.lsp.get_client_by_id(client_id) client.dynamic_capabilities:register(result.registrations) - for bufnr, _ in ipairs(client.attached_buffers) do + for bufnr, _ in pairs(client.attached_buffers) do vim.lsp._set_defaults(client, bufnr) end -- cgit From 80d1333b7317460c562a982ac21f900d9fbd89f6 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Mon, 4 Sep 2023 12:03:03 +0100 Subject: refactor(vim.system): factor out on_exit handling --- runtime/lua/vim/lsp/rpc.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index a77af937b3..6ab5708721 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -648,7 +648,7 @@ function M.start(cmd, cmd_args, dispatchers, extra_spawn_params) dispatchers = merge_dispatchers(dispatchers) - local sysobj ---@type SystemObj + local sysobj ---@type vim.SystemObj local client = new_client(dispatchers, { write = function(msg) @@ -708,7 +708,7 @@ function M.start(cmd, cmd_args, dispatchers, extra_spawn_params) return end - sysobj = sysobj_or_err --[[@as SystemObj]] + sysobj = sysobj_or_err --[[@as vim.SystemObj]] return public_client(client) end -- cgit From 131a1ee82d15ce9d1356a46117c9a1651947d4b8 Mon Sep 17 00:00:00 2001 From: Tom Praschan <13141438+tom-anders@users.noreply.github.com> Date: Thu, 7 Sep 2023 10:12:02 +0200 Subject: feat(lsp): add original LSP Location as item's user_data in locations_to_items (#23743) --- runtime/lua/vim/lsp/util.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 2e376f9093..a6d17afa1b 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1812,6 +1812,9 @@ end) --- Returns the items with the byte position calculated correctly and in sorted --- order, for display in quickfix and location lists. --- +--- The `user_data` field of each resulting item will contain the original +--- `Location` or `LocationLink` it was computed from. +--- --- The result can be passed to the {list} argument of |setqflist()| or --- |setloclist()|. --- @@ -1840,7 +1843,7 @@ function M.locations_to_items(locations, offset_encoding) -- locations may be Location or LocationLink local uri = d.uri or d.targetUri local range = d.range or d.targetSelectionRange - table.insert(grouped[uri], { start = range.start }) + table.insert(grouped[uri], { start = range.start, location = d }) end local keys = vim.tbl_keys(grouped) @@ -1872,6 +1875,7 @@ function M.locations_to_items(locations, offset_encoding) lnum = row + 1, col = col + 1, text = line, + user_data = temp.location, }) end end -- cgit From 5e3cf9fb4bc7f236c858f609ca83c57fb1779ab0 Mon Sep 17 00:00:00 2001 From: Grace Petryk Date: Sun, 10 Sep 2023 01:02:23 -0700 Subject: feat(lsp): improve control over placement of floating windows (#24494) --- runtime/lua/vim/lsp/handlers.lua | 4 ++-- runtime/lua/vim/lsp/util.lua | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index a6b70ac911..81d4d6cceb 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -355,7 +355,7 @@ end ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |nvim_open_win()| +--- - See |vim.lsp.util.open_floating_preview()| for more options. function M.hover(_, result, ctx, config) config = config or {} config.focus_id = ctx.method @@ -442,7 +442,7 @@ M[ms.textDocument_implementation] = location_handler ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |nvim_open_win()| +--- - See |vim.lsp.util.open_floating_preview()| for more options function M.signature_help(_, result, ctx, config) config = config or {} config.focus_id = ctx.method diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index a6d17afa1b..e76fd15612 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1087,6 +1087,12 @@ end --- - focusable (string or table) override `focusable` --- - zindex (string or table) override `zindex`, defaults to 50 --- - relative ("mouse"|"cursor") defaults to "cursor" +--- - anchor_bias ("auto"|"above"|"below") defaults to "auto" +--- - "auto": place window based on which side of the cursor has more lines +--- - "above": place the window above the cursor unless there are not enough lines +--- to display the full window height. +--- - "below": place the window below the cursor unless there are not enough lines +--- to display the full window height. ---@return table Options function M.make_floating_popup_options(width, height, opts) validate({ @@ -1105,7 +1111,20 @@ function M.make_floating_popup_options(width, height, opts) or vim.fn.winline() - 1 local lines_below = vim.fn.winheight(0) - lines_above - if lines_above < lines_below then + local anchor_bias = opts.anchor_bias or 'auto' + + local anchor_below + + if anchor_bias == 'below' then + anchor_below = (lines_below > lines_above) or (height <= lines_below) + elseif anchor_bias == 'above' then + local anchor_above = (lines_above > lines_below) or (height <= lines_above) + anchor_below = not anchor_above + else + anchor_below = lines_below > lines_above + end + + if anchor_below then anchor = anchor .. 'N' height = math.min(lines_below, height) row = 1 @@ -1635,7 +1654,8 @@ end --- ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ----@param opts table with optional fields (additional keys are passed on to |nvim_open_win()|) +---@param opts table with optional fields (additional keys are filtered with |vim.lsp.util.make_floating_popup_options()| +--- before they are passed on to |nvim_open_win()|) --- - height: (integer) height of floating window --- - width: (integer) width of floating window --- - wrap: (boolean, default true) wrap long lines -- cgit From d22172f36bbe147f3aa6b76a1c43ae445f481c2e Mon Sep 17 00:00:00 2001 From: Sergey Slipchenko Date: Mon, 11 Sep 2023 08:16:03 +0400 Subject: fix(api): more intuitive cursor updates in nvim_buf_set_text Fixes #22526 --- runtime/lua/vim/lsp/util.lua | 42 ------------------------------------------ 1 file changed, 42 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index e76fd15612..54721865b7 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -454,23 +454,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) end end) - -- Some LSP servers are depending on the VSCode behavior. - -- The VSCode will re-locate the cursor position after applying TextEdit so we also do it. - local is_current_buf = api.nvim_get_current_buf() == bufnr or bufnr == 0 - local cursor = (function() - if not is_current_buf then - return { - row = -1, - col = -1, - } - end - local cursor = api.nvim_win_get_cursor(0) - return { - row = cursor[1] - 1, - col = cursor[2], - } - end)() - -- save and restore local marks since they get deleted by nvim_buf_set_lines local marks = {} for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do @@ -480,7 +463,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) end -- Apply text edits. - local is_cursor_fixed = false local has_eol_text_edit = false for _, text_edit in ipairs(text_edits) do -- Normalize line ending @@ -527,20 +509,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) e.end_col = math.min(last_line_len, e.end_col) api.nvim_buf_set_text(bufnr, e.start_row, e.start_col, e.end_row, e.end_col, e.text) - - -- Fix cursor position. - local row_count = (e.end_row - e.start_row) + 1 - if e.end_row < cursor.row then - cursor.row = cursor.row + (#e.text - row_count) - is_cursor_fixed = true - elseif e.end_row == cursor.row and e.end_col <= cursor.col then - cursor.row = cursor.row + (#e.text - row_count) - cursor.col = #e.text[#e.text] + (cursor.col - e.end_col) - if #e.text == 1 then - cursor.col = cursor.col + e.start_col - end - is_cursor_fixed = true - end end end @@ -560,16 +528,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) end end - -- Apply fixed cursor position. - if is_cursor_fixed then - local is_valid_cursor = true - is_valid_cursor = is_valid_cursor and cursor.row < max - is_valid_cursor = is_valid_cursor and cursor.col <= #(get_line(bufnr, cursor.row) or '') - if is_valid_cursor then - api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col }) - end - end - -- Remove final line if needed local fix_eol = has_eol_text_edit fix_eol = fix_eol and (vim.bo[bufnr].eol or (vim.bo[bufnr].fixeol and not vim.bo[bufnr].binary)) -- cgit From 2e92065686f62851318150a315591c30b8306a4b Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Thu, 14 Sep 2023 08:23:01 -0500 Subject: docs: replace
 with ``` (#25136)

---
 runtime/lua/vim/lsp/buf.lua             | 23 +++++++++---------
 runtime/lua/vim/lsp/codelens.lua        |  6 ++---
 runtime/lua/vim/lsp/diagnostic.lua      | 10 +++++---
 runtime/lua/vim/lsp/handlers.lua        | 43 +++++++++++++++++++--------------
 runtime/lua/vim/lsp/semantic_tokens.lua |  7 +++---
 5 files changed, 49 insertions(+), 40 deletions(-)

(limited to 'runtime/lua/vim/lsp')

diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua
index 6cd0aa1e95..8a29fac2b5 100644
--- a/runtime/lua/vim/lsp/buf.lua
+++ b/runtime/lua/vim/lsp/buf.lua
@@ -168,13 +168,11 @@ end
 ---
 ---     - filter (function|nil):
 ---         Predicate used to filter clients. Receives a client as argument and must return a
----         boolean. Clients matching the predicate are included. Example:
----
----         
lua
----           -- Never request typescript-language-server for formatting
----           vim.lsp.buf.format {
----             filter = function(client) return client.name ~= "tsserver" end
----           }
+---         boolean. Clients matching the predicate are included. Example: 
lua
+---                     -- Never request typescript-language-server for formatting
+---                     vim.lsp.buf.format {
+---                       filter = function(client) return client.name ~= "tsserver" end
+---                     }
 ---         
--- --- - async boolean|nil @@ -555,11 +553,12 @@ end --- Send request to the server to resolve document highlights for the current --- text document position. This request can be triggered by a key mapping or --- by events such as `CursorHold`, e.g.: ----
vim
----   autocmd CursorHold   lua vim.lsp.buf.document_highlight()
----   autocmd CursorHoldI  lua vim.lsp.buf.document_highlight()
----   autocmd CursorMoved  lua vim.lsp.buf.clear_references()
---- 
+--- +--- ```vim +--- autocmd CursorHold lua vim.lsp.buf.document_highlight() +--- autocmd CursorHoldI lua vim.lsp.buf.document_highlight() +--- autocmd CursorMoved lua vim.lsp.buf.clear_references() +--- ``` --- --- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups --- to be defined or you won't be able to see the actual highlights. diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index d581eb985f..384d09ee48 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -255,10 +255,10 @@ end --- It is recommended to trigger this using an autocmd or via keymap. --- --- Example: ----
vim
----   autocmd BufEnter,CursorHold,InsertLeave  lua vim.lsp.codelens.refresh()
---- 
--- +--- ```vim +--- autocmd BufEnter,CursorHold,InsertLeave lua vim.lsp.codelens.refresh() +--- ``` function M.refresh() local params = { textDocument = util.make_text_document_params(), diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 2a77992c4d..73ffa1a46c 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -203,7 +203,8 @@ end --- --- See |vim.diagnostic.config()| for configuration options. Handler-specific --- configuration can be set using |vim.lsp.with()|: ----
lua
+---
+--- ```lua
 --- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
 ---   vim.lsp.diagnostic.on_publish_diagnostics, {
 ---     -- Enable underline, use default values
@@ -221,7 +222,7 @@ end
 ---     update_in_insert = false,
 ---   }
 --- )
---- 
+--- ``` --- ---@param config table Configuration table (see |vim.diagnostic.config()|). function M.on_publish_diagnostics(_, result, ctx, config) @@ -263,7 +264,8 @@ end --- --- See |vim.diagnostic.config()| for configuration options. Handler-specific --- configuration can be set using |vim.lsp.with()|: ----
lua
+---
+--- ```lua
 --- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with(
 ---   vim.lsp.diagnostic.on_diagnostic, {
 ---     -- Enable underline, use default values
@@ -281,7 +283,7 @@ end
 ---     update_in_insert = false,
 ---   }
 --- )
---- 
+--- ``` --- ---@param config table Configuration table (see |vim.diagnostic.config()|). function M.on_diagnostic(_, result, ctx, config) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 81d4d6cceb..4ea3dde81c 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -342,16 +342,18 @@ M[ms.textDocument_completion] = function(_, result, _, _) end --- |lsp-handler| for the method "textDocument/hover" ----
lua
----   vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
----     vim.lsp.handlers.hover, {
----       -- Use a sharp border with `FloatBorder` highlights
----       border = "single",
----       -- add the title in hover float window
----       title = "hover"
----     }
----   )
---- 
+--- +--- ```lua +--- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( +--- vim.lsp.handlers.hover, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single", +--- -- add the title in hover float window +--- title = "hover" +--- } +--- ) +--- ``` +--- ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window @@ -430,15 +432,20 @@ M[ms.textDocument_typeDefinition] = location_handler M[ms.textDocument_implementation] = location_handler --- |lsp-handler| for the method "textDocument/signatureHelp". +--- --- The active parameter is highlighted with |hl-LspSignatureActiveParameter|. ----
lua
----   vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(
----     vim.lsp.handlers.signature_help, {
----       -- Use a sharp border with `FloatBorder` highlights
----       border = "single"
----     }
----   )
---- 
+--- +--- ```lua +--- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( +--- vim.lsp.handlers.signature_help, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single" +--- } +--- ) +--- ``` +--- +---@param result table Response from the language server +---@param ctx table Client context ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index 5b20344bd3..a5831c0beb 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -555,9 +555,10 @@ local M = {} --- delete the semanticTokensProvider table from the {server_capabilities} of --- your client in your |LspAttach| callback or your configuration's --- `on_attach` callback: ----
lua
----   client.server_capabilities.semanticTokensProvider = nil
---- 
+--- +--- ```lua +--- client.server_capabilities.semanticTokensProvider = nil +--- ``` --- ---@param bufnr integer ---@param client_id integer -- cgit From cfd4a9dfaf5fd900264a946ca33c4a4f26f66a49 Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Tue, 12 Sep 2023 20:51:21 -0700 Subject: feat(lsp): use treesitter for stylize markdown --- runtime/lua/vim/lsp/handlers.lua | 15 +++- runtime/lua/vim/lsp/util.lua | 177 ++++++++++++++++++++++++++------------- 2 files changed, 130 insertions(+), 62 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 4ea3dde81c..f8407be159 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -371,15 +371,22 @@ function M.hover(_, result, ctx, config) end return end - local markdown_lines = util.convert_input_to_markdown_lines(result.contents) - markdown_lines = util.trim_empty_lines(markdown_lines) - if vim.tbl_isempty(markdown_lines) then + local format = 'markdown' + local contents ---@type string[] + if type(result.contents) == 'table' and result.contents.kind == 'plaintext' then + format = 'plaintext' + contents = { result.contents.value or '' } + else + contents = util.convert_input_to_markdown_lines(result.contents) + end + contents = util.trim_empty_lines(contents) + if vim.tbl_isempty(contents) then if config.silent ~= true then vim.notify('No information available') end return end - return util.open_floating_preview(markdown_lines, 'markdown', config) + return util.open_floating_preview(contents, format, config) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 54721865b7..32e85578d3 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -877,9 +877,12 @@ end --- window for `textDocument/hover`, for parsing the result of --- `textDocument/signatureHelp`, and potentially others. --- +--- Note that if the input is of type `MarkupContent` and its kind is `plaintext`, +--- then the corresponding value is returned without further modifications. +--- ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ----@return table {contents} extended with lines of converted markdown. +---@return string[] extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover function M.convert_input_to_markdown_lines(input, contents) contents = contents or {} @@ -887,27 +890,13 @@ function M.convert_input_to_markdown_lines(input, contents) if type(input) == 'string' then list_extend(contents, split_lines(input)) else - assert(type(input) == 'table', 'Expected a table for Hover.contents') + assert(type(input) == 'table', 'Expected a table for LSP input') -- MarkupContent if input.kind then - -- The kind can be either plaintext or markdown. - -- If it's plaintext, then wrap it in a block - - -- Some servers send input.value as empty, so let's ignore this :( local value = input.value or '' - - if input.kind == 'plaintext' then - -- wrap this in a block so that stylize_markdown - -- can properly process it as plaintext - value = string.format('\n%s\n', value) - end - - -- assert(type(value) == 'string') list_extend(contents, split_lines(value)) -- MarkupString variation 2 elseif input.language then - -- Some servers send input.value as empty, so let's ignore this :( - -- assert(type(input.value) == 'string') table.insert(contents, '```' .. input.language) list_extend(contents, split_lines(input.value or '')) table.insert(contents, '```') @@ -925,7 +914,7 @@ function M.convert_input_to_markdown_lines(input, contents) return contents end ---- Converts `textDocument/SignatureHelp` response to markdown lines. +--- Converts `textDocument/signatureHelp` response to markdown lines. --- ---@param signature_help table Response of `textDocument/SignatureHelp` ---@param ft string|nil filetype that will be use as the `lang` for the label markdown code block @@ -955,7 +944,7 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers end local label = signature.label if ft then - -- wrap inside a code block so stylize_markdown can render it properly + -- wrap inside a code block for proper rendering label = ('```%s\n%s\n```'):format(ft, label) end list_extend(contents, split(label, '\n', { plain = true })) @@ -1223,7 +1212,7 @@ function M.preview_location(location, opts) local syntax = vim.bo[bufnr].syntax if syntax == '' then -- When no syntax is set, we use filetype as fallback. This might not result - -- in a valid syntax definition. See also ft detection in stylize_markdown. + -- in a valid syntax definition. -- An empty syntax is more common now with TreeSitter, since TS disables syntax. syntax = vim.bo[bufnr].filetype end @@ -1240,36 +1229,65 @@ local function find_window_by_var(name, value) end end ---- Trims empty lines from input and pad top and bottom with empty lines ---- ----@param contents table of lines to trim and pad ----@param opts table with optional fields ---- - pad_top number of lines to pad contents at top (default 0) ---- - pad_bottom number of lines to pad contents at bottom (default 0) ----@return table table of trimmed and padded lines -function M._trim(contents, opts) - validate({ - contents = { contents, 't' }, - opts = { opts, 't', true }, - }) - opts = opts or {} - contents = M.trim_empty_lines(contents) - if opts.pad_top then - for _ = 1, opts.pad_top do - table.insert(contents, 1, '') +---Returns true if the line is empty or only contains whitespace. +---@param line string +---@return boolean +local function is_blank_line(line) + return line and line:match('^%s*$') +end + +---Returns true if the line corresponds to a Markdown thematic break. +---@param line string +---@return boolean +local function is_separator_line(line) + return line and line:match('^ ? ? ?%-%-%-+%s*$') +end + +---Replaces separator lines by the given divider and removing surrounding blank lines. +---@param contents string[] +---@param divider string +---@return string[] +local function replace_separators(contents, divider) + local trimmed = {} + local l = 1 + while l <= #contents do + local line = contents[l] + if is_separator_line(line) then + if l > 1 and is_blank_line(contents[l - 1]) then + table.remove(trimmed) + end + table.insert(trimmed, divider) + if is_blank_line(contents[l + 1]) then + l = l + 1 + end + else + table.insert(trimmed, line) end + l = l + 1 end - if opts.pad_bottom then - for _ = 1, opts.pad_bottom do - table.insert(contents, '') + + return trimmed +end + +---Collapses successive blank lines in the input table into a single one. +---@param contents string[] +---@return string[] +local function collapse_blank_lines(contents) + local collapsed = {} + local l = 1 + while l <= #contents do + local line = contents[l] + if is_blank_line(line) then + while is_blank_line(contents[l + 1]) do + l = l + 1 + end end + table.insert(collapsed, line) + l = l + 1 end - return contents + return collapsed end ---- Generates a table mapping markdown code block lang to vim syntax, ---- based on g:markdown_fenced_languages ----@return table table of lang -> syntax mappings local function get_markdown_fences() local fences = {} for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do @@ -1297,8 +1315,6 @@ end --- - wrap_at character to wrap at for computing height --- - max_width maximal width of floating window --- - max_height maximal height of floating window ---- - pad_top number of lines to pad contents at top ---- - pad_bottom number of lines to pad contents at bottom --- - separator insert separator after code block ---@return table stripped content function M.stylize_markdown(bufnr, contents, opts) @@ -1335,7 +1351,7 @@ function M.stylize_markdown(bufnr, contents, opts) end -- Clean up - contents = M._trim(contents, opts) + contents = M.trim_empty_lines(contents) local stripped = {} local highlights = {} @@ -1484,6 +1500,49 @@ function M.stylize_markdown(bufnr, contents, opts) return stripped end +--- @class lsp.util.NormalizeMarkdownOptions +--- @field width integer Thematic breaks are expanded to this size. Defaults to 80. + +--- Normalizes Markdown input to a canonical form. +--- +--- The returned Markdown adheres to the GitHub Flavored Markdown (GFM) +--- specification. +--- +--- The following transformations are made: +--- +--- 1. Empty lines at the beginning or end of the content are removed +--- 2. Carriage returns ('\r') are removed +--- 3. Successive empty lines are collapsed into a single empty line +--- 4. Thematic breaks are expanded to the given width +--- +---@private +---@param contents string[] +---@param opts? lsp.util.NormalizeMarkdownOptions +---@return string[] table of lines containing normalized Markdown +---@see https://github.github.com/gfm +function M._normalize_markdown(contents, opts) + validate({ + contents = { contents, 't' }, + opts = { opts, 't', true }, + }) + opts = opts or {} + + -- 1. Empty lines at the beginning or end of the content are removed + contents = M.trim_empty_lines(contents) + + -- 2. Carriage returns are removed + contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n') + + -- 3. Successive empty lines are collapsed into a single empty line + contents = collapse_blank_lines(contents) + + -- 4. Thematic breaks are expanded to the given width + local divider = string.rep('─', opts.width or 80) + contents = replace_separators(contents, divider) + + return contents +end + --- Closes the preview window --- ---@param winnr integer window id of preview window @@ -1620,8 +1679,6 @@ end --- - wrap_at: (integer) character to wrap at for computing height when wrap is enabled --- - max_width: (integer) maximal width of floating window --- - max_height: (integer) maximal height of floating window ---- - pad_top: (integer) number of lines to pad contents at top ---- - pad_bottom: (integer) number of lines to pad contents at bottom --- - focus_id: (string) if a popup with this id is opened, then focus it --- - close_events: (table) list of events that closes the floating window --- - focusable: (boolean, default true) Make float focusable @@ -1629,8 +1686,7 @@ end --- is also `true`, focus an existing floating window with the same --- {focus_id} ---@return integer bufnr of newly created float window ----@return integer winid of newly created float window ----preview window +---@return integer winid of newly created float window preview window function M.open_floating_preview(contents, syntax, opts) validate({ contents = { contents, 't' }, @@ -1639,7 +1695,6 @@ function M.open_floating_preview(contents, syntax, opts) }) opts = opts or {} opts.wrap = opts.wrap ~= false -- wrapping by default - opts.stylize_markdown = opts.stylize_markdown ~= false and vim.g.syntax_on ~= nil opts.focus = opts.focus ~= false opts.close_events = opts.close_events or { 'CursorMoved', 'CursorMovedI', 'InsertCharPre' } @@ -1671,16 +1726,21 @@ function M.open_floating_preview(contents, syntax, opts) api.nvim_win_close(existing_float, true) end + -- Create the buffer local floating_bufnr = api.nvim_create_buf(false, true) - local do_stylize = syntax == 'markdown' and opts.stylize_markdown - - -- Clean up input: trim empty lines from the end, pad - contents = M._trim(contents, opts) + -- Set up the contents, using treesitter for markdown + local do_stylize = syntax == 'markdown' and vim.g.syntax_on ~= nil if do_stylize then - -- applies the syntax and sets the lines to the buffer - contents = M.stylize_markdown(floating_bufnr, contents, opts) + local width = M._make_floating_popup_size(contents, opts) + contents = M._normalize_markdown(contents, { width = width }) + vim.bo[floating_bufnr].filetype = 'markdown' + vim.treesitter.start(floating_bufnr) + api.nvim_buf_set_lines(floating_bufnr, 0, -1, false, contents) else + -- Clean up input: trim empty lines from the end, pad + contents = M.trim_empty_lines(contents) + if syntax then vim.bo[floating_bufnr].syntax = syntax end @@ -1697,9 +1757,9 @@ function M.open_floating_preview(contents, syntax, opts) local float_option = M.make_floating_popup_options(width, height, opts) local floating_winnr = api.nvim_open_win(floating_bufnr, false, float_option) + if do_stylize then vim.wo[floating_winnr].conceallevel = 2 - vim.wo[floating_winnr].concealcursor = 'n' end -- disable folding vim.wo[floating_winnr].foldenable = false @@ -1708,6 +1768,7 @@ function M.open_floating_preview(contents, syntax, opts) vim.bo[floating_bufnr].modifiable = false vim.bo[floating_bufnr].bufhidden = 'wipe' + api.nvim_buf_set_keymap( floating_bufnr, 'n', -- cgit From 5a363ccac8ff5889332bafbf68e7e8d20bca316c Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Mon, 18 Sep 2023 11:04:01 -0700 Subject: fix(lsp)!: deprecate trim_empty_lines --- runtime/lua/vim/lsp/handlers.lua | 4 +--- runtime/lua/vim/lsp/util.lua | 29 +++++++++++++---------------- 2 files changed, 14 insertions(+), 19 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index f8407be159..d43d9a7cfa 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -375,11 +375,10 @@ function M.hover(_, result, ctx, config) local contents ---@type string[] if type(result.contents) == 'table' and result.contents.kind == 'plaintext' then format = 'plaintext' - contents = { result.contents.value or '' } + contents = vim.split(result.contents.value or '', '\n', { trimempty = true }) else contents = util.convert_input_to_markdown_lines(result.contents) end - contents = util.trim_empty_lines(contents) if vim.tbl_isempty(contents) then if config.silent ~= true then vim.notify('No information available') @@ -477,7 +476,6 @@ function M.signature_help(_, result, ctx, config) vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters') local ft = vim.bo[ctx.bufnr].filetype local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers) - lines = util.trim_empty_lines(lines) if vim.tbl_isempty(lines) then if config.silent ~= true then print('No signature help available') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 32e85578d3..988057f5f9 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -102,7 +102,7 @@ end local function split_lines(value) value = string.gsub(value, '\r\n?', '\n') - return split(value, '\n', { plain = true }) + return split(value, '\n', { plain = true, trimempty = true }) end local function create_window_without_focus() @@ -947,7 +947,7 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers -- wrap inside a code block for proper rendering label = ('```%s\n%s\n```'):format(ft, label) end - list_extend(contents, split(label, '\n', { plain = true })) + list_extend(contents, split(label, '\n', { plain = true, trimempty = true })) if signature.documentation then -- if LSP returns plain string, we treat it as plaintext. This avoids -- special characters like underscore or similar from being interpreted @@ -1351,7 +1351,7 @@ function M.stylize_markdown(bufnr, contents, opts) end -- Clean up - contents = M.trim_empty_lines(contents) + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) local stripped = {} local highlights = {} @@ -1510,10 +1510,9 @@ end --- --- The following transformations are made: --- ---- 1. Empty lines at the beginning or end of the content are removed ---- 2. Carriage returns ('\r') are removed ---- 3. Successive empty lines are collapsed into a single empty line ---- 4. Thematic breaks are expanded to the given width +--- 1. Carriage returns ('\r') and empty lines at the beginning and end are removed +--- 2. Successive empty lines are collapsed into a single empty line +--- 3. Thematic breaks are expanded to the given width --- ---@private ---@param contents string[] @@ -1527,16 +1526,13 @@ function M._normalize_markdown(contents, opts) }) opts = opts or {} - -- 1. Empty lines at the beginning or end of the content are removed - contents = M.trim_empty_lines(contents) + -- 1. Carriage returns are removed + contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n', { trimempty = true }) - -- 2. Carriage returns are removed - contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n') - - -- 3. Successive empty lines are collapsed into a single empty line + -- 2. Successive empty lines are collapsed into a single empty line contents = collapse_blank_lines(contents) - -- 4. Thematic breaks are expanded to the given width + -- 3. Thematic breaks are expanded to the given width local divider = string.rep('─', opts.width or 80) contents = replace_separators(contents, divider) @@ -1738,8 +1734,8 @@ function M.open_floating_preview(contents, syntax, opts) vim.treesitter.start(floating_bufnr) api.nvim_buf_set_lines(floating_bufnr, 0, -1, false, contents) else - -- Clean up input: trim empty lines from the end, pad - contents = M.trim_empty_lines(contents) + -- Clean up input: trim empty lines + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) if syntax then vim.bo[floating_bufnr].syntax = syntax @@ -1969,6 +1965,7 @@ function M.symbols_to_items(symbols, bufnr) end --- Removes empty lines from the beginning and end. +---@deprecated use `vim.split()` with `trimempty` instead ---@param lines table list of lines to trim ---@return table trimmed list of lines function M.trim_empty_lines(lines) -- cgit From 8bd6f7c20b403e8031a94f3a158a10c90b5c3efd Mon Sep 17 00:00:00 2001 From: Jaehwang Jung Date: Thu, 21 Sep 2023 16:56:15 +0900 Subject: fix(lsp): clear codelens on LspDetach (#24903) Also fix incorrect parameters in on_detach callback. --- runtime/lua/vim/lsp/codelens.lua | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 384d09ee48..9cccaa1d66 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -8,6 +8,7 @@ local M = {} --- to throttle refreshes to at most one at a time local active_refreshes = {} +---@type table> --- bufnr -> client_id -> lenses local lens_cache_by_buf = setmetatable({}, { __index = function(t, b) @@ -16,6 +17,8 @@ local lens_cache_by_buf = setmetatable({}, { end, }) +---@type table +---client_id -> namespace local namespaces = setmetatable({}, { __index = function(t, key) local value = api.nvim_create_namespace('vim_lsp_codelens:' .. key) @@ -27,6 +30,18 @@ local namespaces = setmetatable({}, { ---@private M.__namespaces = namespaces +local augroup = api.nvim_create_augroup('vim_lsp_codelens', {}) + +api.nvim_create_autocmd('LspDetach', { + group = augroup, + callback = function(ev) + M.clear(ev.data.client_id, ev.buf) + end, +}) + +---@param lens lsp.CodeLens +---@param bufnr integer +---@param client_id integer local function execute_lens(lens, bufnr, client_id) local line = lens.range.start.line api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) @@ -42,7 +57,7 @@ end --- Return all lenses for the given buffer --- ---@param bufnr integer Buffer number. 0 can be used for the current buffer. ----@return table (`CodeLens[]`) +---@return lsp.CodeLens[] function M.get(bufnr) local lenses_by_client = lens_cache_by_buf[bufnr or 0] if not lenses_by_client then @@ -98,12 +113,17 @@ end ---@param client_id integer|nil filter by client_id. All clients if nil ---@param bufnr integer|nil filter by buffer. All buffers if nil function M.clear(client_id, bufnr) - local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(lens_cache_by_buf) + bufnr = bufnr and resolve_bufnr(bufnr) + local buffers = bufnr and { bufnr } + or vim.tbl_filter(api.nvim_buf_is_loaded, api.nvim_list_bufs()) for _, iter_bufnr in pairs(buffers) do local client_ids = client_id and { client_id } or vim.tbl_keys(namespaces) for _, iter_client_id in pairs(client_ids) do local ns = namespaces[iter_client_id] - lens_cache_by_buf[iter_bufnr][iter_client_id] = {} + -- there can be display()ed lenses, which are not stored in cache + if lens_cache_by_buf[iter_bufnr] then + lens_cache_by_buf[iter_bufnr][iter_client_id] = {} + end api.nvim_buf_clear_namespace(iter_bufnr, ns, 0, -1) end end @@ -111,7 +131,7 @@ end --- Display the lenses using virtual text --- ----@param lenses table of lenses to display (`CodeLens[] | null`) +---@param lenses? lsp.CodeLens[] lenses to display ---@param bufnr integer ---@param client_id integer function M.display(lenses, bufnr, client_id) @@ -124,7 +144,8 @@ function M.display(lenses, bufnr, client_id) api.nvim_buf_clear_namespace(bufnr, ns, 0, -1) return end - local lenses_by_lnum = {} + + local lenses_by_lnum = {} ---@type table for _, lens in pairs(lenses) do local line_lenses = lenses_by_lnum[lens.range.start.line] if not line_lenses then @@ -160,7 +181,7 @@ end --- Store lenses for a specific buffer and client --- ----@param lenses table of lenses to store (`CodeLens[] | null`) +---@param lenses? lsp.CodeLens[] lenses to store ---@param bufnr integer ---@param client_id integer function M.save(lenses, bufnr, client_id) @@ -174,7 +195,7 @@ function M.save(lenses, bufnr, client_id) lens_cache_by_buf[bufnr] = lenses_by_client local ns = namespaces[client_id] api.nvim_buf_attach(bufnr, false, { - on_detach = function(b) + on_detach = function(_, b) lens_cache_by_buf[b] = nil end, on_lines = function(_, b, _, first_lnum, last_lnum) @@ -185,6 +206,10 @@ function M.save(lenses, bufnr, client_id) lenses_by_client[client_id] = lenses end +---@param lenses? lsp.CodeLens[] +---@param bufnr integer +---@param client_id integer +---@param callback fun() local function resolve_lenses(lenses, bufnr, client_id, callback) lenses = lenses or {} local num_lens = vim.tbl_count(lenses) -- cgit From 345bd91db28ecfc4deb308f4971253b534f82d49 Mon Sep 17 00:00:00 2001 From: Sergey Slipchenko Date: Thu, 21 Sep 2023 14:06:40 +0400 Subject: fix(lsp): handle absence of a trailing newline #25194 Fixes #24339 rust-analyzer sends "Invalid offset" error in such cases. Some other servers handle it specially. LSP spec mentions that "A range is comparable to a selection in an editor". Most editors don't handle trailing newlines the same way Neovim/Vim does, it's clearly visible if it's present or not. With that in mind it's understandable why sending end position as simply the start of the line after the last one is considered invalid in such cases. --- runtime/lua/vim/lsp/util.lua | 60 ++++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 16 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 988057f5f9..0d1e3cc0d1 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2230,6 +2230,35 @@ function M.lookup_section(settings, section) return settings end +--- Converts line range (0-based, end-inclusive) to lsp range, +--- handles absence of a trailing newline +--- +---@param bufnr integer +---@param start_line integer +---@param end_line integer +---@param offset_encoding lsp.PositionEncodingKind +---@return lsp.Range +local function make_line_range_params(bufnr, start_line, end_line, offset_encoding) + local last_line = api.nvim_buf_line_count(bufnr) - 1 + + ---@type lsp.Position + local end_pos + + if end_line == last_line and not vim.api.nvim_get_option_value('endofline', { buf = bufnr }) then + end_pos = { + line = end_line, + character = M.character_offset(bufnr, end_line, #get_line(bufnr, end_line), offset_encoding), + } + else + end_pos = { line = end_line + 1, character = 0 } + end + + return { + start = { line = start_line, character = 0 }, + ['end'] = end_pos, + } +end + ---@private --- Request updated LSP information for a buffer. --- @@ -2253,6 +2282,8 @@ function M._refresh(method, opts) return end + local textDocument = M.make_text_document_params(bufnr) + local only_visible = opts.only_visible or false if only_visible then @@ -2260,28 +2291,25 @@ function M._refresh(method, opts) if api.nvim_win_get_buf(window) == bufnr then local first = vim.fn.line('w0', window) local last = vim.fn.line('w$', window) - local params = { - textDocument = M.make_text_document_params(bufnr), - range = { - start = { line = first - 1, character = 0 }, - ['end'] = { line = last, character = 0 }, - }, - } for _, client in ipairs(clients) do - client.request(method, params, nil, bufnr) + client.request(method, { + textDocument = textDocument, + range = make_line_range_params(bufnr, first - 1, last - 1, client.offset_encoding), + }, nil, bufnr) end end end else - local params = { - textDocument = M.make_text_document_params(bufnr), - range = { - start = { line = 0, character = 0 }, - ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, - }, - } for _, client in ipairs(clients) do - client.request(method, params, nil, bufnr) + client.request(method, { + textDocument = textDocument, + range = make_line_range_params( + bufnr, + 0, + api.nvim_buf_line_count(bufnr) - 1, + client.offset_encoding + ), + }, nil, bufnr) end end end -- cgit From d1bc6fca7123d77ebf03d0badd63f930a5b74064 Mon Sep 17 00:00:00 2001 From: Bogdan Grigoruță <43993819+krady21@users.noreply.github.com> Date: Sun, 24 Sep 2023 21:43:16 +0300 Subject: feat(health): list attached buffers in LSP report #23561 Problem: Users using `vim.lsp.start` directly (instead of nvim-lspconfig) need more visibility for troubleshooting. For example, troubleshooting unnecesary servers or servers that aren't attaching to expected buffers. Solution: Mention attached buffers in the `:checkhealth lsp` report. Example: vim.lsp: Active Clients ~ - clangd (id=1, root_dir=~/dev/neovim, attached_to=[7]) - lua_ls (id=2, root_dir=~/dev/neovim, attached_to=[10]) --- runtime/lua/vim/lsp/health.lua | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 023b1c26be..fe06006108 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -32,8 +32,15 @@ function M.check() vim.health.start('vim.lsp: Active Clients') if next(clients) then for _, client in pairs(clients) do + local attached_to = table.concat(vim.tbl_keys(client.attached_buffers or {}), ',') report_info( - string.format('%s (id=%s, root_dir=%s)', client.name, client.id, client.config.root_dir) + string.format( + '%s (id=%s, root_dir=%s, attached_to=[%s])', + client.name, + client.id, + vim.fn.fnamemodify(client.config.root_dir, ':~'), + attached_to + ) ) end else -- cgit From 9ed830a3ca5847a9152b91fca5e1eaf712bed55b Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Fri, 29 Sep 2023 08:37:14 -0700 Subject: refactor(lsp): deprecate util methods (#25400) --- runtime/lua/vim/lsp/util.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 0d1e3cc0d1..51ed87219c 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -168,10 +168,12 @@ end local _str_utfindex_enc = M._str_utfindex_enc local _str_byteindex_enc = M._str_byteindex_enc + --- Replaces text in a range with new text. --- --- CAUTION: Changes in-place! --- +---@deprecated ---@param lines (table) Original list of strings ---@param A (table) Start position; a 2-tuple of {line,col} numbers ---@param B (table) End position; a 2-tuple of {line,col} numbers @@ -320,9 +322,7 @@ local function get_line(bufnr, row) end --- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position ---- Returns a zero-indexed column, since set_lines() does the conversion to ---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---- 1-indexed ---@return integer local function get_line_byte_from_position(bufnr, position, offset_encoding) -- LSP's line and characters are 0-indexed @@ -1991,6 +1991,7 @@ end --- --- CAUTION: Modifies the input in-place! --- +---@deprecated ---@param lines table list of lines ---@return string filetype or "markdown" if it was unchanged. function M.try_trim_markdown_code_blocks(lines) -- cgit From 4a09c178a19097c295521892c889f1f196fff100 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 2 Oct 2023 22:14:19 +0200 Subject: feat(lsp): fallback to code-action command on resolve failure (#25464) The haskell-language-server supports resolve only for a subset of code actions. For many code actions trying to resolve the `edit` property results in an error, but the unresolved action already contains a command that can be executed without issue. The protocol specification is unfortunately a bit vague about this, and what the haskell-language-server does seems to be valid. Example: newtype Dummy = Dummy Int instance Num Dummy where Triggering code actions on "Num Dummy" and choosing "Add placeholders for all missing methods" resulted in: -32601: No plugin enabled for SMethod_CodeActionResolve, potentially available: explicit-fields, importLens, hlint, overloaded-record-dot With this change it will insert the missing methods: instance Num Dummy where (+) = _ (-) = _ (*) = _ negate = _ abs = _ signum = _ fromInteger = _ --- runtime/lua/vim/lsp/buf.lua | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 8a29fac2b5..a906512e24 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -652,7 +652,7 @@ local function on_code_action_results(results, ctx, options) -- arguments?: any[] -- ---@type lsp.Client - local client = vim.lsp.get_client_by_id(action_tuple[1]) + local client = assert(vim.lsp.get_client_by_id(action_tuple[1])) local action = action_tuple[2] local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = ctx.bufnr }) @@ -663,10 +663,14 @@ local function on_code_action_results(results, ctx, options) if not action.edit and client and supports_resolve then client.request(ms.codeAction_resolve, action, function(err, resolved_action) if err then - vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) - return + if action.command then + apply_action(action, client) + else + vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) + end + else + apply_action(resolved_action, client) end - apply_action(resolved_action, client) end, ctx.bufnr) else apply_action(action, client) -- cgit From f736b075d371dd15fa6fffc907db7952bc19bb9d Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Sun, 1 Oct 2023 09:53:18 -0700 Subject: feat(lsp): snippet parsing using lpeg --- runtime/lua/vim/lsp/_snippet_grammar.lua | 143 +++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 runtime/lua/vim/lsp/_snippet_grammar.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua new file mode 100644 index 0000000000..86f00fea51 --- /dev/null +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -0,0 +1,143 @@ +--- Grammar for LSP snippets, based on https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#snippet_syntax + +local lpeg = vim.lpeg +local P, S, R, V = lpeg.P, lpeg.S, lpeg.R, lpeg.V +local C, Cg, Ct = lpeg.C, lpeg.Cg, lpeg.Ct + +local M = {} + +local alpha = R('az', 'AZ') +local backslash = P('\\') +local colon = P(':') +local dollar = P('$') +local int = R('09') ^ 1 +local l_brace, r_brace = P('{'), P('}') +local pipe = P('|') +local slash = P('/') +local underscore = P('_') +local var = Cg((underscore + alpha) * ((underscore + alpha + int) ^ 0), 'name') +local format_capture = Cg(int / tonumber, 'capture') +local format_modifier = Cg(P('upcase') + P('downcase') + P('capitalize'), 'modifier') +local tabstop = Cg(int / tonumber, 'tabstop') + +--- Returns a function that unescapes occurrences of "special" characters. +--- +--- @param special string +--- @return fun(match: string): string +local function escape_text(special) + return function(match) + local escaped = match:gsub('\\(.)', function(c) + return special:find(c) and c or '\\' .. c + end) + return escaped + end +end + +-- Text nodes match "any character", but $, \, and } must be escaped. +local escapable = '$}\\' +local text = (backslash * S(escapable)) + (P(1) - S(escapable)) +local text_0, text_1 = (text ^ 0) / escape_text(escapable), text ^ 1 +-- Within choice nodes, \ also escapes comma and pipe characters. +local choice_text = C(((backslash * S(escapable .. ',|')) + (P(1) - S(escapable .. ',|'))) ^ 1) + / escape_text(escapable .. ',|') +local if_text, else_text = Cg(text_0, 'if_text'), Cg(text_0, 'else_text') +-- Within format nodes, make sure we stop at / +local format_text = C(((backslash * S(escapable)) + (P(1) - S(escapable .. '/'))) ^ 1) + / escape_text(escapable) +-- Within ternary condition format nodes, make sure we stop at : +local if_till_colon_text = Cg( + C(((backslash * S(escapable)) + (P(1) - S(escapable .. ':'))) ^ 1) / escape_text(escapable), + 'if_text' +) + +-- Matches the string inside //, allowing escaping of the closing slash. +local regex = Cg(((backslash * slash) + (P(1) - slash)) ^ 1, 'regex') + +-- Regex constructor flags (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#parameters). +local options = Cg(S('dgimsuvy') ^ 0, 'options') + +--- @enum vim.snippet.Type +local Type = { + Tabstop = 1, + Placeholder = 2, + Choice = 3, + Variable = 4, + Format = 5, + Text = 6, + Snippet = 7, +} +M.NodeType = Type + +--- @class vim.snippet.Node: { type: vim.snippet.Type, data: T } +--- @class vim.snippet.TabstopData: { tabstop: number } +--- @class vim.snippet.TextData: { text: string } +--- @class vim.snippet.PlaceholderData: { tabstop: vim.snippet.TabstopData, value: vim.snippet.Node } +--- @class vim.snippet.ChoiceData: { tabstop: vim.snippet.TabstopData, values: string[] } +--- @class vim.snippet.VariableData: { name: string, default?: vim.snippet.Node, regex?: string, format?: vim.snippet.Node[], options?: string } +--- @class vim.snippet.FormatData: { capture: number, modifier?: string, if_text?: string, else_text?: string } +--- @class vim.snippet.SnippetData: { children: vim.snippet.Node[] } + +--- Returns a function that constructs a snippet node of the given type. +--- +--- @generic T +--- @param type vim.snippet.Type +--- @return fun(data: T): vim.snippet.Node +local function node(type) + return function(data) + return { type = type, data = data } + end +end + +-- stylua: ignore +local G = P({ + 'snippet'; + snippet = Ct(Cg( + Ct(( + V('any') + + (Ct(Cg(text_1 / escape_text(escapable), 'text')) / node(Type.Text)) + ) ^ 1), 'children' + )) / node(Type.Snippet), + any_or_text = V('any') + (Ct(Cg(text_0 / escape_text(escapable), 'text')) / node(Type.Text)), + any = V('placeholder') + V('tabstop') + V('choice') + V('variable'), + tabstop = Ct(dollar * (tabstop + (l_brace * tabstop * r_brace))) / node(Type.Tabstop), + placeholder = Ct(dollar * l_brace * tabstop * colon * Cg(V('any_or_text'), 'value') * r_brace) / node(Type.Placeholder), + choice = Ct(dollar * + l_brace * + tabstop * + pipe * + Cg(Ct(choice_text * (P(',') * choice_text) ^ 0), 'values') * + pipe * + r_brace) / node(Type.Choice), + variable = Ct(dollar * ( + var + ( + l_brace * var * ( + r_brace + + (colon * Cg(V('any_or_text'), 'default') * r_brace) + + (slash * regex * slash * Cg(Ct((V('format') + (C(format_text) / node(Type.Text))) ^ 1), 'format') * slash * options * r_brace) + )) + )) / node(Type.Variable), + format = Ct(dollar * ( + format_capture + ( + l_brace * format_capture * ( + r_brace + + (colon * ( + (slash * format_modifier * r_brace) + + (P('+') * if_text * r_brace) + + (P('?') * if_till_colon_text * colon * else_text * r_brace) + + (P('-') * else_text * r_brace) + + (else_text * r_brace) + )) + )) + )) / node(Type.Format), +}) + +--- Parses the given input into a snippet tree. +--- @param input string +--- @return vim.snippet.Node +function M.parse(input) + local snippet = G:match(input) + assert(snippet, 'snippet parsing failed') + return snippet --- @type vim.snippet.Node +end + +return M -- cgit From eb1f0e8fcca756a00d287e23bf87554e0e7f6dfd Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Sun, 1 Oct 2023 09:54:04 -0700 Subject: feat(lsp)!: replace snippet parser by lpeg grammar --- runtime/lua/vim/lsp/_snippet.lua | 500 --------------------------------------- runtime/lua/vim/lsp/util.lua | 35 ++- 2 files changed, 32 insertions(+), 503 deletions(-) delete mode 100644 runtime/lua/vim/lsp/_snippet.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet.lua b/runtime/lua/vim/lsp/_snippet.lua deleted file mode 100644 index e7ada5415f..0000000000 --- a/runtime/lua/vim/lsp/_snippet.lua +++ /dev/null @@ -1,500 +0,0 @@ -local P = {} - ----Take characters until the target characters (The escape sequence is '\' + char) ----@param targets string[] The character list for stop consuming text. ----@param specials string[] If the character isn't contained in targets/specials, '\' will be left. -P.take_until = function(targets, specials) - targets = targets or {} - specials = specials or {} - - return function(input, pos) - local new_pos = pos - local raw = {} - local esc = {} - while new_pos <= #input do - local c = string.sub(input, new_pos, new_pos) - if c == '\\' then - table.insert(raw, '\\') - new_pos = new_pos + 1 - c = string.sub(input, new_pos, new_pos) - 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.list_contains(targets, c) then - break - end - table.insert(raw, c) - table.insert(esc, c) - new_pos = new_pos + 1 - end - end - - if new_pos == pos then - return P.unmatch(pos) - end - - return { - parsed = true, - value = { - raw = table.concat(raw, ''), - esc = table.concat(esc, ''), - }, - pos = new_pos, - } - end -end - -P.unmatch = function(pos) - return { - parsed = false, - value = nil, - pos = pos, - } -end - -P.map = function(parser, map) - return function(input, pos) - local result = parser(input, pos) - if result.parsed then - return { - parsed = true, - value = map(result.value), - pos = result.pos, - } - end - return P.unmatch(pos) - end -end - -P.lazy = function(factory) - return function(input, pos) - return factory()(input, pos) - end -end - -P.token = function(token) - return function(input, pos) - local maybe_token = string.sub(input, pos, pos + #token - 1) - if token == maybe_token then - return { - parsed = true, - value = maybe_token, - pos = pos + #token, - } - end - return P.unmatch(pos) - end -end - -P.pattern = function(p) - return function(input, pos) - local maybe_match = string.match(string.sub(input, pos), '^' .. p) - if maybe_match then - return { - parsed = true, - value = maybe_match, - pos = pos + #maybe_match, - } - end - return P.unmatch(pos) - end -end - -P.many = function(parser) - return function(input, pos) - local values = {} - local new_pos = pos - while new_pos <= #input do - local result = parser(input, new_pos) - if not result.parsed then - break - end - table.insert(values, result.value) - new_pos = result.pos - end - if #values > 0 then - return { - parsed = true, - value = values, - pos = new_pos, - } - end - return P.unmatch(pos) - end -end - -P.any = function(...) - local parsers = { ... } - return function(input, pos) - for _, parser in ipairs(parsers) do - local result = parser(input, pos) - if result.parsed then - return result - end - end - return P.unmatch(pos) - end -end - -P.opt = function(parser) - return function(input, pos) - local result = parser(input, pos) - return { - parsed = true, - value = result.value, - pos = result.pos, - } - end -end - -P.seq = function(...) - local parsers = { ... } - return function(input, pos) - local values = {} - local new_pos = pos - for i, parser in ipairs(parsers) do - local result = parser(input, new_pos) - if result.parsed then - values[i] = result.value - new_pos = result.pos - else - return P.unmatch(pos) - end - end - return { - parsed = true, - value = values, - pos = new_pos, - } - end -end - -local Node = {} - -Node.Type = { - SNIPPET = 0, - TABSTOP = 1, - PLACEHOLDER = 2, - VARIABLE = 3, - CHOICE = 4, - TRANSFORM = 5, - FORMAT = 6, - TEXT = 7, -} - -function Node:__tostring() - local insert_text = {} - if self.type == Node.Type.SNIPPET then - for _, c in ipairs(self.children) do - table.insert(insert_text, tostring(c)) - end - elseif self.type == Node.Type.CHOICE then - table.insert(insert_text, self.items[1]) - elseif self.type == Node.Type.PLACEHOLDER then - for _, c in ipairs(self.children or {}) do - table.insert(insert_text, tostring(c)) - end - elseif self.type == Node.Type.TEXT then - table.insert(insert_text, self.esc) - end - return table.concat(insert_text, '') -end - ---@see https://code.visualstudio.com/docs/editor/userdefinedsnippets#_grammar - -local S = {} -S.dollar = P.token('$') -S.open = P.token('{') -S.close = P.token('}') -S.colon = P.token(':') -S.slash = P.token('/') -S.comma = P.token(',') -S.pipe = P.token('|') -S.plus = P.token('+') -S.minus = P.token('-') -S.question = P.token('?') -S.int = P.map(P.pattern('[0-9]+'), function(value) - return tonumber(value, 10) -end) -S.var = P.pattern('[%a_][%w_]+') -S.text = function(targets, specials) - return P.map(P.take_until(targets, specials), function(value) - return setmetatable({ - type = Node.Type.TEXT, - raw = value.raw, - esc = value.esc, - }, Node) - end) -end - -S.toplevel = P.lazy(function() - return P.any(S.placeholder, S.tabstop, S.variable, S.choice) -end) - -S.format = P.any( - P.map(P.seq(S.dollar, S.int), function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.close), function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - }, Node) - end), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - S.slash, - P.any( - P.token('upcase'), - P.token('downcase'), - P.token('capitalize'), - P.token('camelcase'), - P.token('pascalcase') - ), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - modifier = values[6], - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.seq( - S.question, - P.opt(P.take_until({ ':' }, { '\\' })), - S.colon, - P.opt(P.take_until({ '}' }, { '\\' })) - ), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = values[5][2] and values[5][2].esc or '', - else_text = values[5][4] and values[5][4].esc or '', - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.seq(S.plus, P.opt(P.take_until({ '}' }, { '\\' }))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = values[5][2] and values[5][2].esc or '', - else_text = '', - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - S.minus, - P.opt(P.take_until({ '}' }, { '\\' })), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = '', - else_text = values[6] and values[6].esc or '', - }, Node) - end - ), - P.map( - P.seq(S.dollar, S.open, S.int, S.colon, P.opt(P.take_until({ '}' }, { '\\' })), S.close), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = '', - else_text = values[5] and values[5].esc or '', - }, Node) - end - ) -) - -S.transform = P.map( - P.seq( - S.slash, - P.take_until({ '/' }, { '\\' }), - S.slash, - P.many(P.any(S.format, S.text({ '$', '/' }, { '\\' }))), - S.slash, - P.opt(P.pattern('[ig]+')) - ), - function(values) - return setmetatable({ - type = Node.Type.TRANSFORM, - pattern = values[2].raw, - format = values[4], - option = values[6], - }, Node) - end -) - -S.tabstop = P.any( - P.map(P.seq(S.dollar, S.int), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.close), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[3], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.transform, S.close), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[3], - transform = values[4], - }, Node) - end) -) - -S.placeholder = P.any( - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.opt(P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' })))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.PLACEHOLDER, - tabstop = values[3], - -- insert empty text if opt did not match. - children = values[5] or { - setmetatable({ - type = Node.Type.TEXT, - raw = '', - esc = '', - }, Node), - }, - }, Node) - end - ) -) - -S.choice = P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.pipe, - P.many(P.map(P.seq(S.text({ ',', '|' }), P.opt(S.comma)), function(values) - return values[1].esc - end)), - S.pipe, - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.CHOICE, - tabstop = values[3], - items = values[5], - }, Node) - end -) - -S.variable = P.any( - P.map(P.seq(S.dollar, S.var), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.var, S.close), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.var, S.transform, S.close), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - transform = values[4], - }, Node) - end), - P.map( - P.seq( - S.dollar, - S.open, - S.var, - S.colon, - P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' }))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - children = values[5], - }, Node) - end - ) -) - -S.snippet = P.map(P.many(P.any(S.toplevel, S.text({ '$' }, { '}', '\\' }))), function(values) - return setmetatable({ - type = Node.Type.SNIPPET, - children = values, - }, Node) -end) - -local M = {} - ----The snippet node type enum ----@types table -M.NodeType = Node.Type - ----Parse snippet string and returns the AST ----@param input string ----@return table -function M.parse(input) - local result = S.snippet(input, 1) - if not result.parsed then - error('snippet parsing failed.') - end - return result.value -end - -return M diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 51ed87219c..a4c8959b99 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1,5 +1,5 @@ local protocol = require('vim.lsp.protocol') -local snippet = require('vim.lsp._snippet') +local snippet = require('vim.lsp._snippet_grammar') local validate = vim.validate local api = vim.api local list_extend = vim.list_extend @@ -610,12 +610,41 @@ end ---@return string parsed snippet function M.parse_snippet(input) local ok, parsed = pcall(function() - return tostring(snippet.parse(input)) + return snippet.parse(input) end) if not ok then return input end - return parsed + + --- @param node vim.snippet.Node + --- @return string + local function node_to_string(node) + local insert_text = {} + if node.type == snippet.NodeType.Snippet then + for _, child in + ipairs((node.data --[[@as vim.snippet.SnippetData]]).children) + do + table.insert(insert_text, node_to_string(child)) + end + elseif node.type == snippet.NodeType.Choice then + table.insert(insert_text, (node.data --[[@as vim.snippet.ChoiceData]]).values[1]) + elseif node.type == snippet.NodeType.Placeholder then + table.insert( + insert_text, + node_to_string((node.data --[[@as vim.snippet.PlaceholderData]]).value) + ) + elseif node.type == snippet.NodeType.Text then + table.insert( + insert_text, + node + .data --[[@as vim.snippet.TextData]] + .text + ) + end + return table.concat(insert_text) + end + + return node_to_string(parsed) end --- Sorts by CompletionItem.sortText. -- cgit From 9abced6ad95f6300ae80cd8b8aa124ebcf511b50 Mon Sep 17 00:00:00 2001 From: LW Date: Sun, 8 Oct 2023 01:09:25 -0700 Subject: fix(lsp): account for border height in max floating popup height (#25539) --- runtime/lua/vim/lsp/util.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index a4c8959b99..ec0a1b0ab0 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1100,13 +1100,14 @@ function M.make_floating_popup_options(width, height, opts) anchor_below = lines_below > lines_above end + local border_height = get_border_size(opts).height if anchor_below then anchor = anchor .. 'N' - height = math.min(lines_below, height) + height = math.max(math.min(lines_below - border_height, height), 0) row = 1 else anchor = anchor .. 'S' - height = math.min(lines_above, height) + height = math.max(math.min(lines_above - border_height, height), 0) row = 0 end -- cgit From 840e1864c2de2b4b192a4df1865b69093904b139 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 12 Oct 2023 15:39:39 +0800 Subject: fix(lsp): handle NUL bytes in popup text (#25612) Fix #25610 --- runtime/lua/vim/lsp/util.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index ec0a1b0ab0..7e6855528a 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1647,7 +1647,7 @@ function M._make_floating_popup_size(contents, opts) width = 0 for i, line in ipairs(contents) do -- TODO(ashkan) use nvim_strdisplaywidth if/when that is introduced. - line_widths[i] = vim.fn.strdisplaywidth(line) + line_widths[i] = vim.fn.strdisplaywidth(line:gsub('%z', '\n')) width = math.max(line_widths[i], width) end end @@ -1676,7 +1676,7 @@ function M._make_floating_popup_size(contents, opts) height = 0 if vim.tbl_isempty(line_widths) then for _, line in ipairs(contents) do - local line_width = vim.fn.strdisplaywidth(line) + local line_width = vim.fn.strdisplaywidth(line:gsub('%z', '\n')) height = height + math.ceil(line_width / wrap_at) end else -- cgit From ee156ca60ede95c95160cb8dff0197d40cb1a491 Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Sat, 14 Oct 2023 00:06:40 -0700 Subject: fix(lsp): refactor escaping snippet text (#25611) --- runtime/lua/vim/lsp/_snippet_grammar.lua | 48 ++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 18 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua index 86f00fea51..eb72efdf39 100644 --- a/runtime/lua/vim/lsp/_snippet_grammar.lua +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -20,11 +20,15 @@ local format_capture = Cg(int / tonumber, 'capture') local format_modifier = Cg(P('upcase') + P('downcase') + P('capitalize'), 'modifier') local tabstop = Cg(int / tonumber, 'tabstop') +-- These characters are always escapable in text nodes no matter the context. +local escapable = '$}\\' + --- Returns a function that unescapes occurrences of "special" characters. --- ---- @param special string +--- @param special? string --- @return fun(match: string): string local function escape_text(special) + special = special or escapable return function(match) local escaped = match:gsub('\\(.)', function(c) return special:find(c) and c or '\\' .. c @@ -33,25 +37,33 @@ local function escape_text(special) end end --- Text nodes match "any character", but $, \, and } must be escaped. -local escapable = '$}\\' -local text = (backslash * S(escapable)) + (P(1) - S(escapable)) -local text_0, text_1 = (text ^ 0) / escape_text(escapable), text ^ 1 +--- Returns a pattern for text nodes. Will match characters in `escape` when preceded by a backslash, +--- and will stop with characters in `stop_with`. +--- +--- @param escape string +--- @param stop_with? string +--- @return vim.lpeg.Pattern +local function text(escape, stop_with) + stop_with = stop_with or escape + return (backslash * S(escape)) + (P(1) - S(stop_with)) +end + +-- For text nodes inside curly braces. It stops parsing when reaching an escapable character. +local braced_text = (text(escapable) ^ 0) / escape_text() + -- Within choice nodes, \ also escapes comma and pipe characters. -local choice_text = C(((backslash * S(escapable .. ',|')) + (P(1) - S(escapable .. ',|'))) ^ 1) - / escape_text(escapable .. ',|') -local if_text, else_text = Cg(text_0, 'if_text'), Cg(text_0, 'else_text') +local choice_text = C(text(escapable .. ',|') ^ 1) / escape_text(escapable .. ',|') + -- Within format nodes, make sure we stop at / -local format_text = C(((backslash * S(escapable)) + (P(1) - S(escapable .. '/'))) ^ 1) - / escape_text(escapable) +local format_text = C(text(escapable, escapable .. '/') ^ 1) / escape_text() + +local if_text, else_text = Cg(braced_text, 'if_text'), Cg(braced_text, 'else_text') + -- Within ternary condition format nodes, make sure we stop at : -local if_till_colon_text = Cg( - C(((backslash * S(escapable)) + (P(1) - S(escapable .. ':'))) ^ 1) / escape_text(escapable), - 'if_text' -) +local if_till_colon_text = Cg(C(text(escapable, escapable .. ':') ^ 1) / escape_text(), 'if_text') -- Matches the string inside //, allowing escaping of the closing slash. -local regex = Cg(((backslash * slash) + (P(1) - slash)) ^ 1, 'regex') +local regex = Cg(text('/') ^ 1, 'regex') -- Regex constructor flags (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#parameters). local options = Cg(S('dgimsuvy') ^ 0, 'options') @@ -94,11 +106,11 @@ local G = P({ snippet = Ct(Cg( Ct(( V('any') + - (Ct(Cg(text_1 / escape_text(escapable), 'text')) / node(Type.Text)) + (Ct(Cg((text(escapable, '$') ^ 1) / escape_text(), 'text')) / node(Type.Text)) ) ^ 1), 'children' - )) / node(Type.Snippet), - any_or_text = V('any') + (Ct(Cg(text_0 / escape_text(escapable), 'text')) / node(Type.Text)), + ) * -P(1)) / node(Type.Snippet), any = V('placeholder') + V('tabstop') + V('choice') + V('variable'), + any_or_text = V('any') + (Ct(Cg(braced_text, 'text')) / node(Type.Text)), tabstop = Ct(dollar * (tabstop + (l_brace * tabstop * r_brace))) / node(Type.Tabstop), placeholder = Ct(dollar * l_brace * tabstop * colon * Cg(V('any_or_text'), 'value') * r_brace) / node(Type.Placeholder), choice = Ct(dollar * -- cgit From 712adacdf546fbaccd9f2134534889a3f6f36dbc Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sat, 14 Oct 2023 09:47:20 +0200 Subject: refactor(lsp): make is_pull in lsp.diagnostic.get_namespace optional (#25156) Follw up to https://github.com/neovim/neovim/commit/63b3408551561127f7845470eb51404bcd6f547b `is_pull` should be optional, otherwise it is an API change that introduces warnings in consumers. Also fixes the type annotation of `_client_pull_namespaces` where the key is a string. --- runtime/lua/vim/lsp/diagnostic.lua | 41 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 20 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 73ffa1a46c..73444d8c6a 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -159,44 +159,45 @@ local function diagnostic_vim_to_lsp(diagnostics) end, diagnostics) end ----@type table +---@type table local _client_push_namespaces = {} ----@type table + +---@type table local _client_pull_namespaces = {} --- Get the diagnostic namespace associated with an LSP client |vim.diagnostic| for diagnostics --- ---@param client_id integer The id of the LSP client ----@param is_pull boolean Whether the namespace is for a pull or push client +---@param is_pull boolean? Whether the namespace is for a pull or push client. Defaults to push function M.get_namespace(client_id, is_pull) vim.validate({ client_id = { client_id, 'n' } }) - local namespace_table - local key - local name local client = vim.lsp.get_client_by_id(client_id) - if is_pull then - namespace_table = _client_pull_namespaces - local server_id = vim.tbl_get(client.server_capabilities, 'diagnosticProvider', 'identifier') - key = string.format('%d:%s', client_id, server_id or 'nil') - name = string.format( + local server_id = + vim.tbl_get((client or {}).server_capabilities, 'diagnosticProvider', 'identifier') + local key = string.format('%d:%s', client_id, server_id or 'nil') + local name = string.format( 'vim.lsp.%s.%d.%s', client and client.name or 'unknown', client_id, server_id or 'nil' ) + local ns = _client_pull_namespaces[key] + if not ns then + ns = api.nvim_create_namespace(name) + _client_pull_namespaces[key] = ns + end + return ns else - namespace_table = _client_push_namespaces - key = client_id - name = string.format('vim.lsp.%s.%d', client and client.name or 'unknown', client_id) - end - - if not namespace_table[key] then - namespace_table[key] = api.nvim_create_namespace(name) + local name = string.format('vim.lsp.%s.%d', client and client.name or 'unknown', client_id) + local ns = _client_push_namespaces[client_id] + if not ns then + ns = api.nvim_create_namespace(name) + _client_push_namespaces[client_id] = ns + end + return ns end - - return namespace_table[key] end --- |lsp-handler| for the method "textDocument/publishDiagnostics" -- cgit From 57ce9b6a92977fb11269d99be0bb06eab18eda75 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Sat, 14 Oct 2023 11:31:16 +0200 Subject: refactor(lsp): fix luals warnings in tagfunc and add type annotations (#25150) --- runtime/lua/vim/lsp/tagfunc.lua | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index 957449743b..4ad50e4a58 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -2,6 +2,11 @@ local lsp = vim.lsp local util = lsp.util local ms = lsp.protocol.Methods +---@param name string +---@param range lsp.Range +---@param uri string +---@param offset_encoding string +---@return {name: string, filename: string, cmd: string, kind?: string} local function mk_tag_item(name, range, uri, offset_encoding) local bufnr = vim.uri_to_bufnr(uri) -- This is get_line_byte_from_position is 0-indexed, call cursor expects a 1-indexed position @@ -13,6 +18,8 @@ local function mk_tag_item(name, range, uri, offset_encoding) } end +---@param pattern string +---@return table[] local function query_definition(pattern) local params = util.make_position_params() local results_by_client, err = lsp.buf_request_sync(0, ms.textDocument_definition, params, 1000) @@ -23,17 +30,19 @@ local function query_definition(pattern) local add = function(range, uri, offset_encoding) table.insert(results, mk_tag_item(pattern, range, uri, offset_encoding)) end - for client_id, lsp_results in pairs(results_by_client) do + for client_id, lsp_results in pairs(assert(results_by_client)) do local client = lsp.get_client_by_id(client_id) + local offset_encoding = client and client.offset_encoding or 'utf-16' local result = lsp_results.result or {} if result.range then -- Location add(result.range, result.uri) - else -- Location[] or LocationLink[] + else + result = result --[[@as (lsp.Location[]|lsp.LocationLink[])]] for _, item in pairs(result) do if item.range then -- Location - add(item.range, item.uri, client.offset_encoding) + add(item.range, item.uri, offset_encoding) else -- LocationLink - add(item.targetSelectionRange, item.targetUri, client.offset_encoding) + add(item.targetSelectionRange, item.targetUri, offset_encoding) end end end @@ -41,6 +50,8 @@ local function query_definition(pattern) return results end +---@param pattern string +---@return table[] local function query_workspace_symbols(pattern) local results_by_client, err = lsp.buf_request_sync(0, ms.workspace_symbol, { query = pattern }, 1000) @@ -48,11 +59,13 @@ local function query_workspace_symbols(pattern) return {} end local results = {} - for client_id, symbols in pairs(results_by_client) do + for client_id, responses in pairs(assert(results_by_client)) do local client = lsp.get_client_by_id(client_id) - for _, symbol in pairs(symbols.result or {}) do + local offset_encoding = client and client.offset_encoding or 'utf-16' + local symbols = responses.result --[[@as lsp.SymbolInformation[]|nil]] + for _, symbol in pairs(symbols or {}) do local loc = symbol.location - local item = mk_tag_item(symbol.name, loc.range, loc.uri, client.offset_encoding) + local item = mk_tag_item(symbol.name, loc.range, loc.uri, offset_encoding) item.kind = lsp.protocol.SymbolKind[symbol.kind] or 'Unknown' table.insert(results, item) end @@ -61,12 +74,8 @@ local function query_workspace_symbols(pattern) end local function tagfunc(pattern, flags) - local matches - if string.match(flags, 'c') then - matches = query_definition(pattern) - else - matches = query_workspace_symbols(pattern) - end + local matches = string.match(flags, 'c') and query_definition(pattern) + or query_workspace_symbols(pattern) -- fall back to tags if no matches return #matches > 0 and matches or vim.NIL end -- cgit From c46a6c065e8d830adb8a2f410d3c92cf5bd4455b Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Mon, 16 Oct 2023 08:13:37 -0700 Subject: docs: do not hardcode LSP version in URL #25648 --- runtime/lua/vim/lsp/_snippet_grammar.lua | 2 +- runtime/lua/vim/lsp/buf.lua | 2 +- runtime/lua/vim/lsp/handlers.lua | 2 +- runtime/lua/vim/lsp/sync.lua | 2 +- runtime/lua/vim/lsp/util.lua | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua index eb72efdf39..0a4d669fb9 100644 --- a/runtime/lua/vim/lsp/_snippet_grammar.lua +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -1,4 +1,4 @@ ---- Grammar for LSP snippets, based on https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#snippet_syntax +--- Grammar for LSP snippets, based on https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax local lpeg = vim.lpeg local P, S, R, V = lpeg.P, lpeg.S, lpeg.R, lpeg.V diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index a906512e24..9436fbbf56 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -159,7 +159,7 @@ end --- - formatting_options (table|nil): --- Can be used to specify FormattingOptions. Some unspecified options will be --- automatically derived from the current Nvim options. ---- See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions +--- See https://microsoft.github.io/language-server-protocol/specification/#formattingOptions --- - timeout_ms (integer|nil, default 1000): --- Time in milliseconds to block for formatting requests. No effect if async=true --- - bufnr (number|nil): diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index d43d9a7cfa..d3b199b866 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -623,7 +623,7 @@ M[ms.window_showDocument] = function(_, result, ctx, _) return { success = success or false } end ----@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh +---@see https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh M[ms.workspace_inlayHint_refresh] = function(err, result, ctx, config) return require('vim.lsp.inlay_hint').on_refresh(err, result, ctx, config) end diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index 9c1bbf3892..ca01cdc08b 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -387,7 +387,7 @@ end ---@param lastline integer line to begin search in old_lines for last difference ---@param new_lastline integer line to begin search in new_lines for last difference ---@param offset_encoding string encoding requested by language server ----@return table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent +---@return table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent function M.compute_diff( prev_lines, curr_lines, diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 7e6855528a..d525cae4c0 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1829,7 +1829,7 @@ do --[[ References ]] ---@param bufnr integer Buffer id ---@param references table List of `DocumentHighlight` objects to highlight ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32". - ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent + ---@see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent function M.buf_highlight_references(bufnr, references, offset_encoding) validate({ bufnr = { bufnr, 'n', true }, -- cgit From 2eecb1b85dbb0e02ec40e95d28d3cc4720040f01 Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Mon, 16 Oct 2023 08:52:48 -0700 Subject: fix(lsp): highlight active parameter in signature help #25663 Fixes #25662 --- runtime/lua/vim/lsp/handlers.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index d3b199b866..d153b956ee 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -476,7 +476,7 @@ function M.signature_help(_, result, ctx, config) vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters') local ft = vim.bo[ctx.bufnr].filetype local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers) - if vim.tbl_isempty(lines) then + if not lines or vim.tbl_isempty(lines) then if config.silent ~= true then print('No signature help available') end @@ -484,7 +484,9 @@ function M.signature_help(_, result, ctx, config) end local fbuf, fwin = util.open_floating_preview(lines, 'markdown', config) if hl then - api.nvim_buf_add_highlight(fbuf, -1, 'LspSignatureActiveParameter', 0, unpack(hl)) + -- Highlight the second line if the signature is wrapped in a Markdown code block. + local line = vim.startswith(lines[1], '```') and 1 or 0 + api.nvim_buf_add_highlight(fbuf, -1, 'LspSignatureActiveParameter', line, unpack(hl)) end return fbuf, fwin end -- cgit From 330444994616e48e5e4d15bbf72d7c5346943565 Mon Sep 17 00:00:00 2001 From: Jorge Mederos <46798594+jmederosalvarado@users.noreply.github.com> Date: Sat, 21 Oct 2023 08:47:14 +0200 Subject: fix(lsp): log unknown diagnostic tags instead of showing a warning (#25705) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To be more in line with the specification: > To support the evolution of enumerations the using side of an enumeration shouldn’t fail on an enumeration value it doesn’t know. It should simply ignore it as a value it can use and try to do its best to preserve the value on round trips --- runtime/lua/vim/lsp/diagnostic.lua | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 73444d8c6a..b6f0cfa0b3 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -2,6 +2,7 @@ local util = require('vim.lsp.util') local protocol = require('vim.lsp.protocol') +local log = require('vim.lsp.log') local ms = protocol.Methods local api = vim.api @@ -88,10 +89,7 @@ local function tags_lsp_to_vim(diagnostic, client_id) tags = tags or {} tags.deprecated = true else - vim.notify_once( - string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id), - vim.log.levels.WARN - ) + log.info(string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id)) end end return tags -- cgit From f1775da07fe48da629468bcfcc2a8a6c4c3f40ed Mon Sep 17 00:00:00 2001 From: Maria José Solano Date: Fri, 20 Oct 2023 23:51:26 -0700 Subject: feat(lsp): add snippet API (#25301) --- runtime/lua/vim/lsp/_snippet_grammar.lua | 34 ++++++++++++++++++++++++++++---- runtime/lua/vim/lsp/protocol.lua | 1 - runtime/lua/vim/lsp/util.lua | 30 +--------------------------- 3 files changed, 31 insertions(+), 34 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua index 0a4d669fb9..9318fefcbc 100644 --- a/runtime/lua/vim/lsp/_snippet_grammar.lua +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -81,14 +81,40 @@ local Type = { M.NodeType = Type --- @class vim.snippet.Node: { type: vim.snippet.Type, data: T } ---- @class vim.snippet.TabstopData: { tabstop: number } +--- @class vim.snippet.TabstopData: { tabstop: integer } --- @class vim.snippet.TextData: { text: string } ---- @class vim.snippet.PlaceholderData: { tabstop: vim.snippet.TabstopData, value: vim.snippet.Node } ---- @class vim.snippet.ChoiceData: { tabstop: vim.snippet.TabstopData, values: string[] } +--- @class vim.snippet.PlaceholderData: { tabstop: integer, value: vim.snippet.Node } +--- @class vim.snippet.ChoiceData: { tabstop: integer, values: string[] } --- @class vim.snippet.VariableData: { name: string, default?: vim.snippet.Node, regex?: string, format?: vim.snippet.Node[], options?: string } --- @class vim.snippet.FormatData: { capture: number, modifier?: string, if_text?: string, else_text?: string } --- @class vim.snippet.SnippetData: { children: vim.snippet.Node[] } +--- @type vim.snippet.Node +local Node = {} + +--- @return string +--- @diagnostic disable-next-line: inject-field +function Node:__tostring() + local node_text = {} + local type, data = self.type, self.data + if type == Type.Snippet then + --- @cast data vim.snippet.SnippetData + for _, child in ipairs(data.children) do + table.insert(node_text, tostring(child)) + end + elseif type == Type.Choice then + --- @cast data vim.snippet.ChoiceData + table.insert(node_text, data.values[1]) + elseif type == Type.Placeholder then + --- @cast data vim.snippet.PlaceholderData + table.insert(node_text, tostring(data.value)) + elseif type == Type.Text then + --- @cast data vim.snippet.TextData + table.insert(node_text, data.text) + end + return table.concat(node_text) +end + --- Returns a function that constructs a snippet node of the given type. --- --- @generic T @@ -96,7 +122,7 @@ M.NodeType = Type --- @return fun(data: T): vim.snippet.Node local function node(type) return function(data) - return { type = type, data = data } + return setmetatable({ type = type, data = data }, Node) end end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 0755fa991f..3a1b16c450 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -742,7 +742,6 @@ function protocol.make_client_capabilities() -- this should be disabled out of the box. -- However, users can turn this back on if they have a snippet plugin. snippetSupport = false, - commitCharactersSupport = false, preselectSupport = false, deprecatedSupport = false, diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index d525cae4c0..42c1508cbf 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -616,35 +616,7 @@ function M.parse_snippet(input) return input end - --- @param node vim.snippet.Node - --- @return string - local function node_to_string(node) - local insert_text = {} - if node.type == snippet.NodeType.Snippet then - for _, child in - ipairs((node.data --[[@as vim.snippet.SnippetData]]).children) - do - table.insert(insert_text, node_to_string(child)) - end - elseif node.type == snippet.NodeType.Choice then - table.insert(insert_text, (node.data --[[@as vim.snippet.ChoiceData]]).values[1]) - elseif node.type == snippet.NodeType.Placeholder then - table.insert( - insert_text, - node_to_string((node.data --[[@as vim.snippet.PlaceholderData]]).value) - ) - elseif node.type == snippet.NodeType.Text then - table.insert( - insert_text, - node - .data --[[@as vim.snippet.TextData]] - .text - ) - end - return table.concat(insert_text) - end - - return node_to_string(parsed) + return tostring(parsed) end --- Sorts by CompletionItem.sortText. -- cgit From 1e10310f4cc70cf95a68457c2be9e7459b5bbba6 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Sat, 21 Oct 2023 09:47:24 +0200 Subject: refactor(lsp): move completion logic into _completion module To reduce cross-chatter between modules and for https://github.com/neovim/neovim/issues/25272 Also preparing for https://github.com/neovim/neovim/issues/25714 --- runtime/lua/vim/lsp/_completion.lua | 210 ++++++++++++++++++++++++++++++++++++ runtime/lua/vim/lsp/protocol.lua | 1 + runtime/lua/vim/lsp/util.lua | 93 +--------------- 3 files changed, 214 insertions(+), 90 deletions(-) create mode 100644 runtime/lua/vim/lsp/_completion.lua (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_completion.lua b/runtime/lua/vim/lsp/_completion.lua new file mode 100644 index 0000000000..efd1aaacf7 --- /dev/null +++ b/runtime/lua/vim/lsp/_completion.lua @@ -0,0 +1,210 @@ +local M = {} +local api = vim.api +local lsp = vim.lsp +local protocol = lsp.protocol +local ms = protocol.Methods + +---@param input string unparsed snippet +---@return string parsed snippet +local function parse_snippet(input) + local ok, parsed = pcall(function() + return require('vim.lsp._snippet_grammar').parse(input) + end) + return ok and tostring(parsed) or input +end + +--- Returns text that should be inserted when selecting completion item. The +--- precedence is as follows: textEdit.newText > insertText > label +--- +--- See https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion +--- +---@param item lsp.CompletionItem +---@return string +local function get_completion_word(item) + if item.textEdit ~= nil and item.textEdit.newText ~= nil and item.textEdit.newText ~= '' then + if item.insertTextFormat == protocol.InsertTextFormat.PlainText then + return item.textEdit.newText + else + return parse_snippet(item.textEdit.newText) + end + elseif item.insertText ~= nil and item.insertText ~= '' then + if item.insertTextFormat == protocol.InsertTextFormat.PlainText then + return item.insertText + else + return parse_snippet(item.insertText) + end + end + return item.label +end + +---@param result lsp.CompletionList|lsp.CompletionItem[] +---@return lsp.CompletionItem[] +local function get_items(result) + if result.items then + return result.items + end + return result +end + +--- Turns the result of a `textDocument/completion` request into vim-compatible +--- |complete-items|. +--- +---@param result lsp.CompletionList|lsp.CompletionItem[] Result of `textDocument/completion` +---@param prefix string prefix to filter the completion items +---@return table[] +---@see complete-items +function M._lsp_to_complete_items(result, prefix) + local items = get_items(result) + if vim.tbl_isempty(items) then + return {} + end + + local function matches_prefix(item) + return vim.startswith(get_completion_word(item), prefix) + end + + items = vim.tbl_filter(matches_prefix, items) --[[@as lsp.CompletionItem[]|]] + table.sort(items, function(a, b) + return (a.sortText or a.label) < (b.sortText or b.label) + end) + + local matches = {} + for _, item in ipairs(items) do + local info = '' + local documentation = item.documentation + if documentation then + if type(documentation) == 'string' and documentation ~= '' then + info = documentation + elseif type(documentation) == 'table' and type(documentation.value) == 'string' then + info = documentation.value + else + vim.notify( + ('invalid documentation value %s'):format(vim.inspect(documentation)), + vim.log.levels.WARN + ) + end + end + local word = get_completion_word(item) + table.insert(matches, { + word = word, + abbr = item.label, + kind = protocol.CompletionItemKind[item.kind] or 'Unknown', + menu = item.detail or '', + info = #info > 0 and info or nil, + icase = 1, + dup = 1, + empty = 1, + user_data = { + nvim = { + lsp = { + completion_item = item, + }, + }, + }, + }) + end + return matches +end + +---@param items lsp.CompletionItem[] +local function adjust_start_col(lnum, line, items, encoding) + local min_start_char = nil + for _, item in pairs(items) do + if item.textEdit and item.textEdit.range.start.line == lnum - 1 then + if min_start_char and min_start_char ~= item.textEdit.range.start.character then + return nil + end + min_start_char = item.textEdit.range.start.character + end + end + if min_start_char then + return vim.lsp.util._str_byteindex_enc(line, min_start_char, encoding) + else + return nil + end +end + +---@param findstart integer 0 or 1, decides behavior +---@param base integer findstart=0, text to match against +---@return integer|table Decided by {findstart}: +--- - findstart=0: column where the completion starts, or -2 or -3 +--- - findstart=1: list of matches (actually just calls |complete()|) +function M.omnifunc(findstart, base) + local bufnr = api.nvim_get_current_buf() + local clients = lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_completion }) + local remaining = #clients + if remaining == 0 then + return findstart == 1 and -1 or {} + end + + local log = require('vim.lsp.log') + -- Then, perform standard completion request + if log.info() then + log.info('base ', base) + end + + local win = api.nvim_get_current_win() + local pos = api.nvim_win_get_cursor(win) + local line = api.nvim_get_current_line() + local line_to_cursor = line:sub(1, pos[2]) + log.trace('omnifunc.line', pos, line) + + local word_boundary = vim.fn.match(line_to_cursor, '\\k*$') + 1 --[[@as integer]] + local items = {} + local startbyte = nil + + local function on_done() + local mode = api.nvim_get_mode()['mode'] + if mode == 'i' or mode == 'ic' then + vim.fn.complete(startbyte or word_boundary, items) + end + end + + local util = vim.lsp.util + for _, client in ipairs(clients) do + local params = util.make_position_params(win, client.offset_encoding) + client.request(ms.textDocument_completion, params, function(err, result) + if err then + log.warn(err.message) + end + if result and vim.fn.mode() == 'i' then + -- Completion response items may be relative to a position different than `textMatch`. + -- Concrete example, with sumneko/lua-language-server: + -- + -- require('plenary.asy| + -- ▲ ▲ ▲ + -- │ │ └── cursor_pos: 20 + -- │ └────── textMatch: 17 + -- └────────────── textEdit.range.start.character: 9 + -- .newText = 'plenary.async' + -- ^^^ + -- prefix (We'd remove everything not starting with `asy`, + -- so we'd eliminate the `plenary.async` result + -- + -- `adjust_start_col` is used to prefer the language server boundary. + -- + local encoding = client.offset_encoding + local candidates = get_items(result) + local curstartbyte = adjust_start_col(pos[1], line, candidates, encoding) + if startbyte == nil then + startbyte = curstartbyte + elseif curstartbyte ~= nil and curstartbyte ~= startbyte then + startbyte = word_boundary + end + local prefix = startbyte and line:sub(startbyte + 1) or line_to_cursor:sub(word_boundary) + local matches = M._lsp_to_complete_items(result, prefix) + vim.list_extend(items, matches) + end + remaining = remaining - 1 + if remaining == 0 then + vim.schedule(on_done) + end + end, bufnr) + end + + -- Return -2 to signal that we should continue completion so that we can + -- async complete. + return -2 +end + +return M diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 3a1b16c450..7a48c800c6 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -242,6 +242,7 @@ local constants = { -- Defines whether the insert text in a completion item should be interpreted as -- plain text or a snippet. + --- @enum lsp.InsertTextFormat InsertTextFormat = { -- The primary text to be inserted is treated as a plain string. PlainText = 1, diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 42c1508cbf..7ccb8a38b1 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -548,7 +548,7 @@ end --- `textDocument/completion` request, which may return one of --- `CompletionItem[]`, `CompletionList` or null. ---@param result table The result of a `textDocument/completion` request ----@return table List of completion items +---@return lsp.CompletionItem[] List of completion items ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion function M.extract_completion_items(result) if type(result) == 'table' and result.items then @@ -619,47 +619,6 @@ function M.parse_snippet(input) return tostring(parsed) end ---- Sorts by CompletionItem.sortText. ---- ---see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -local function sort_completion_items(items) - table.sort(items, function(a, b) - return (a.sortText or a.label) < (b.sortText or b.label) - end) -end - ---- Returns text that should be inserted when selecting completion item. The ---- precedence is as follows: textEdit.newText > insertText > label ---see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -local function get_completion_word(item) - if item.textEdit ~= nil and item.textEdit.newText ~= nil and item.textEdit.newText ~= '' then - local insert_text_format = protocol.InsertTextFormat[item.insertTextFormat] - if insert_text_format == 'PlainText' or insert_text_format == nil then - return item.textEdit.newText - else - return M.parse_snippet(item.textEdit.newText) - end - elseif item.insertText ~= nil and item.insertText ~= '' then - local insert_text_format = protocol.InsertTextFormat[item.insertTextFormat] - if insert_text_format == 'PlainText' or insert_text_format == nil then - return item.insertText - else - return M.parse_snippet(item.insertText) - end - end - return item.label -end - ---- Some language servers return complementary candidates whose prefixes do not ---- match are also returned. So we exclude completion candidates whose prefix ---- does not match. -local function remove_unmatch_completion_items(items, prefix) - return vim.tbl_filter(function(item) - local word = get_completion_word(item) - return vim.startswith(word, prefix) - end, items) -end - --- According to LSP spec, if the client set `completionItemKind.valueSet`, --- the client must handle it properly even if it receives a value outside the --- specification. @@ -678,56 +637,10 @@ end --- from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, --- `CompletionList` or `null` ---@param prefix (string) the prefix to filter the completion items ----@return table { matches = complete-items table, incomplete = bool } +---@return table[] items ---@see complete-items function M.text_document_completion_list_to_complete_items(result, prefix) - local items = M.extract_completion_items(result) - if vim.tbl_isempty(items) then - return {} - end - - items = remove_unmatch_completion_items(items, prefix) - sort_completion_items(items) - - local matches = {} - - for _, completion_item in ipairs(items) do - local info = '' - local documentation = completion_item.documentation - if documentation then - if type(documentation) == 'string' and documentation ~= '' then - info = documentation - elseif type(documentation) == 'table' and type(documentation.value) == 'string' then - info = documentation.value - else - vim.notify( - ('invalid documentation value %s'):format(vim.inspect(documentation)), - vim.log.levels.WARN - ) - end - end - - local word = get_completion_word(completion_item) - table.insert(matches, { - word = word, - abbr = completion_item.label, - kind = M._get_completion_item_kind_name(completion_item.kind), - menu = completion_item.detail or '', - info = #info > 0 and info or nil, - icase = 1, - dup = 1, - empty = 1, - user_data = { - nvim = { - lsp = { - completion_item = completion_item, - }, - }, - }, - }) - end - - return matches + return require('vim.lsp._completion')._lsp_to_complete_items(result, prefix) end --- Like vim.fn.bufwinid except it works across tabpages. -- cgit From 195301c60969c7ce97b1ef3a3caaf4965da1abd5 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Sat, 21 Oct 2023 09:57:50 +0200 Subject: refactor(lsp): deprecate completion util methods Relates to https://github.com/neovim/neovim/issues/25272 --- runtime/lua/vim/lsp/util.lua | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 7ccb8a38b1..32b220746f 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -547,10 +547,12 @@ end --- Can be used to extract the completion items from a --- `textDocument/completion` request, which may return one of --- `CompletionItem[]`, `CompletionList` or null. +---@deprecated ---@param result table The result of a `textDocument/completion` request ---@return lsp.CompletionItem[] List of completion items ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion function M.extract_completion_items(result) + vim.deprecate('vim.lsp.util.extract_completion_items', nil, '0.11') if type(result) == 'table' and result.items then -- result is a `CompletionList` return result.items @@ -606,9 +608,11 @@ end --- Parses snippets in a completion entry. --- +---@deprecated ---@param input string unparsed snippet ---@return string parsed snippet function M.parse_snippet(input) + vim.deprecate('vim.lsp.util.parse_snippet', nil, '0.11') local ok, parsed = pcall(function() return snippet.parse(input) end) @@ -619,20 +623,10 @@ function M.parse_snippet(input) return tostring(parsed) end ---- According to LSP spec, if the client set `completionItemKind.valueSet`, ---- the client must handle it properly even if it receives a value outside the ---- specification. ---- ----@param completion_item_kind (`vim.lsp.protocol.completionItemKind`) ----@return (`vim.lsp.protocol.completionItemKind`) ----@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -function M._get_completion_item_kind_name(completion_item_kind) - return protocol.CompletionItemKind[completion_item_kind] or 'Unknown' -end - --- Turns the result of a `textDocument/completion` request into vim-compatible --- |complete-items|. --- +---@deprecated ---@param result table The result of a `textDocument/completion` call, e.g. --- from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, --- `CompletionList` or `null` @@ -640,6 +634,7 @@ end ---@return table[] items ---@see complete-items function M.text_document_completion_list_to_complete_items(result, prefix) + vim.deprecate('vim.lsp.util.text_document_completion_list_to_complete_items', nil, '0.11') return require('vim.lsp._completion')._lsp_to_complete_items(result, prefix) end -- cgit From 5e5f5174e3faa862a9bc353aa7da41487911140b Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Sat, 21 Oct 2023 13:44:53 +0200 Subject: fix(lsp): fix off-by-one error for omnifunc word boundary Fixes https://github.com/neovim/neovim/issues/25177 I initially wanted to split this into a refactor commit to make it more testable, but it appears that already accidentally fixed the issue by normalizing lnum/col to 0-indexing --- runtime/lua/vim/lsp/_completion.lua | 104 ++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 40 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_completion.lua b/runtime/lua/vim/lsp/_completion.lua index efd1aaacf7..f0e3af7f03 100644 --- a/runtime/lua/vim/lsp/_completion.lua +++ b/runtime/lua/vim/lsp/_completion.lua @@ -106,11 +106,12 @@ function M._lsp_to_complete_items(result, prefix) return matches end +---@param lnum integer 0-indexed ---@param items lsp.CompletionItem[] local function adjust_start_col(lnum, line, items, encoding) local min_start_char = nil for _, item in pairs(items) do - if item.textEdit and item.textEdit.range.start.line == lnum - 1 then + if item.textEdit and item.textEdit.range.start.line == lnum then if min_start_char and min_start_char ~= item.textEdit.range.start.character then return nil end @@ -124,12 +125,57 @@ local function adjust_start_col(lnum, line, items, encoding) end end +---@private +---@param line string line content +---@param lnum integer 0-indexed line number +---@param client_start_boundary integer 0-indexed word boundary +---@param server_start_boundary? integer 0-indexed word boundary, based on textEdit.range.start.character +---@param result lsp.CompletionList|lsp.CompletionItem[] +---@param encoding string +---@return table[] matches +---@return integer? server_start_boundary +function M._convert_results( + line, + lnum, + client_start_boundary, + server_start_boundary, + result, + encoding +) + -- Completion response items may be relative to a position different than `client_start_boundary`. + -- Concrete example, with lua-language-server: + -- + -- require('plenary.asy| + -- ▲ ▲ ▲ + -- │ │ └── cursor_pos: 20 + -- │ └────── client_start_boundary: 17 + -- └────────────── textEdit.range.start.character: 9 + -- .newText = 'plenary.async' + -- ^^^ + -- prefix (We'd remove everything not starting with `asy`, + -- so we'd eliminate the `plenary.async` result + -- + -- `adjust_start_col` is used to prefer the language server boundary. + -- + local candidates = get_items(result) + local curstartbyte = adjust_start_col(lnum, line, candidates, encoding) + if server_start_boundary == nil then + server_start_boundary = curstartbyte + elseif curstartbyte ~= nil and curstartbyte ~= server_start_boundary then + server_start_boundary = client_start_boundary + end + local prefix = line:sub((server_start_boundary or client_start_boundary) + 1) + local matches = M._lsp_to_complete_items(result, prefix) + return matches, server_start_boundary +end + ---@param findstart integer 0 or 1, decides behavior ---@param base integer findstart=0, text to match against ---@return integer|table Decided by {findstart}: --- - findstart=0: column where the completion starts, or -2 or -3 --- - findstart=1: list of matches (actually just calls |complete()|) function M.omnifunc(findstart, base) + assert(base) -- silence luals local bufnr = api.nvim_get_current_buf() local clients = lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_completion }) local remaining = #clients @@ -137,26 +183,20 @@ function M.omnifunc(findstart, base) return findstart == 1 and -1 or {} end - local log = require('vim.lsp.log') - -- Then, perform standard completion request - if log.info() then - log.info('base ', base) - end - local win = api.nvim_get_current_win() - local pos = api.nvim_win_get_cursor(win) + local cursor = api.nvim_win_get_cursor(win) + local lnum = cursor[1] - 1 + local cursor_col = cursor[2] local line = api.nvim_get_current_line() - local line_to_cursor = line:sub(1, pos[2]) - log.trace('omnifunc.line', pos, line) - - local word_boundary = vim.fn.match(line_to_cursor, '\\k*$') + 1 --[[@as integer]] + local line_to_cursor = line:sub(1, cursor_col) + local client_start_boundary = vim.fn.match(line_to_cursor, '\\k*$') --[[@as integer]] + local server_start_boundary = nil local items = {} - local startbyte = nil local function on_done() local mode = api.nvim_get_mode()['mode'] if mode == 'i' or mode == 'ic' then - vim.fn.complete(startbyte or word_boundary, items) + vim.fn.complete((server_start_boundary or client_start_boundary) + 1, items) end end @@ -165,34 +205,18 @@ function M.omnifunc(findstart, base) local params = util.make_position_params(win, client.offset_encoding) client.request(ms.textDocument_completion, params, function(err, result) if err then - log.warn(err.message) + require('vim.lsp.log').warn(err.message) end if result and vim.fn.mode() == 'i' then - -- Completion response items may be relative to a position different than `textMatch`. - -- Concrete example, with sumneko/lua-language-server: - -- - -- require('plenary.asy| - -- ▲ ▲ ▲ - -- │ │ └── cursor_pos: 20 - -- │ └────── textMatch: 17 - -- └────────────── textEdit.range.start.character: 9 - -- .newText = 'plenary.async' - -- ^^^ - -- prefix (We'd remove everything not starting with `asy`, - -- so we'd eliminate the `plenary.async` result - -- - -- `adjust_start_col` is used to prefer the language server boundary. - -- - local encoding = client.offset_encoding - local candidates = get_items(result) - local curstartbyte = adjust_start_col(pos[1], line, candidates, encoding) - if startbyte == nil then - startbyte = curstartbyte - elseif curstartbyte ~= nil and curstartbyte ~= startbyte then - startbyte = word_boundary - end - local prefix = startbyte and line:sub(startbyte + 1) or line_to_cursor:sub(word_boundary) - local matches = M._lsp_to_complete_items(result, prefix) + local matches + matches, server_start_boundary = M._convert_results( + line, + lnum, + client_start_boundary, + server_start_boundary, + result, + client.offset_encoding + ) vim.list_extend(items, matches) end remaining = remaining - 1 -- cgit From ba6761eafe615a7f904c585dba3b7d6e98f665e1 Mon Sep 17 00:00:00 2001 From: Lajos Koszti Date: Thu, 26 Oct 2023 22:40:36 +0200 Subject: fix(lsp): fix omnicomplete in middle of the line (#25787) Fixes a regression from 5e5f5174e3faa862a9bc353aa7da41487911140b Until that commit we had a logic like this: `local prefix = startbyte and line:sub(startbyte + 1) or line_to_cursor:sub(word_boundary)` The commit changed the logic and no longer cut off the line at the cursor, resulting in a prefix that included trailing characters --- runtime/lua/vim/lsp/_completion.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_completion.lua b/runtime/lua/vim/lsp/_completion.lua index f0e3af7f03..7a607d6c13 100644 --- a/runtime/lua/vim/lsp/_completion.lua +++ b/runtime/lua/vim/lsp/_completion.lua @@ -137,6 +137,7 @@ end function M._convert_results( line, lnum, + cursor_col, client_start_boundary, server_start_boundary, result, @@ -164,7 +165,7 @@ function M._convert_results( elseif curstartbyte ~= nil and curstartbyte ~= server_start_boundary then server_start_boundary = client_start_boundary end - local prefix = line:sub((server_start_boundary or client_start_boundary) + 1) + local prefix = line:sub((server_start_boundary or client_start_boundary) + 1, cursor_col) local matches = M._lsp_to_complete_items(result, prefix) return matches, server_start_boundary end @@ -212,6 +213,7 @@ function M.omnifunc(findstart, base) matches, server_start_boundary = M._convert_results( line, lnum, + cursor_col, client_start_boundary, server_start_boundary, result, -- cgit From adbe7f368397da21465f27181e254dd3694820e9 Mon Sep 17 00:00:00 2001 From: Evgeni Chasnovski Date: Tue, 31 Oct 2023 14:18:44 +0200 Subject: fix(lsp): call `on_list()` even for single location (#25830) Problem: Currently there is no way of customizing behavior of `declaration`, `definition`, `typeDefinition`, and `implementation` methods in `vim.lsp.buf` when LSP server returns `Location`. Instead, cursor jumps to that location directly. Solution: Normalize LSP response to be `Location[]` for those four cases. --- runtime/lua/vim/lsp/buf.lua | 12 ++++++++---- runtime/lua/vim/lsp/handlers.lua | 31 +++++++++++++++---------------- 2 files changed, 23 insertions(+), 20 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 9436fbbf56..b9b7aefae6 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -62,7 +62,8 @@ end --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.declaration(options) local params = util.make_position_params() request_with_options(ms.textDocument_declaration, params, options) @@ -72,7 +73,8 @@ end --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.definition(options) local params = util.make_position_params() request_with_options(ms.textDocument_definition, params, options) @@ -82,7 +84,8 @@ end --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.type_definition(options) local params = util.make_position_params() request_with_options(ms.textDocument_typeDefinition, params, options) @@ -92,7 +95,8 @@ end --- quickfix window. --- ---@param options table|nil additional options ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.implementation(options) local params = util.make_position_params() request_with_options(ms.textDocument_implementation, params, options) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index d153b956ee..6fde55cf04 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -407,25 +407,24 @@ local function location_handler(_, result, ctx, config) -- textDocument/definition can return Location or Location[] -- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition + if not vim.tbl_islist(result) then + result = { result } + end - if vim.tbl_islist(result) then - local title = 'LSP locations' - local items = util.locations_to_items(result, client.offset_encoding) + local title = 'LSP locations' + local items = util.locations_to_items(result, client.offset_encoding) - if config.on_list then - assert(type(config.on_list) == 'function', 'on_list is not a function') - config.on_list({ title = title, items = items }) - else - if #result == 1 then - util.jump_to_location(result[1], client.offset_encoding, config.reuse_win) - return - end - vim.fn.setqflist({}, ' ', { title = title, items = items }) - api.nvim_command('botright copen') - end - else - util.jump_to_location(result, client.offset_encoding, config.reuse_win) + if config.on_list then + assert(type(config.on_list) == 'function', 'on_list is not a function') + config.on_list({ title = title, items = items }) + return + end + if #result == 1 then + util.jump_to_location(result[1], client.offset_encoding, config.reuse_win) + return end + vim.fn.setqflist({}, ' ', { title = title, items = items }) + api.nvim_command('botright copen') end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration -- cgit From 9281edb334a374e7753d4a6b7a05e31120e39772 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Thu, 2 Nov 2023 09:59:41 +0100 Subject: fix(lsp): create per client params in lsp.buf.code_action `code_action` used the same parameters for all clients, which led to the following warning and incorrect start/end column locations if using clients with mixed encodings: warning: multiple different client offset_encodings detected for buffer, this is not supported yet --- runtime/lua/vim/lsp/buf.lua | 141 ++++++++++++++++++++++++++++---------------- 1 file changed, 91 insertions(+), 50 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index b9b7aefae6..cf9acc0808 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -579,6 +579,17 @@ function M.clear_references() util.buf_clear_references() end +---@class vim.lsp.CodeActionResultEntry +---@field error? lsp.ResponseError +---@field result? (lsp.Command|lsp.CodeAction)[] +---@field ctx lsp.HandlerContext + +---@class vim.lsp.buf.code_action.opts +---@field context? lsp.CodeActionContext +---@field filter? fun(x: lsp.CodeAction|lsp.Command):boolean +---@field apply? boolean +---@field range? {start: integer[], end: integer[]} + --- This is not public because the main extension point is --- vim.ui.select which can be overridden independently. --- @@ -587,17 +598,18 @@ end --- from multiple clients to have 1 single UI prompt for the user, yet we still --- need to be able to link a `CodeAction|Command` to the right client for --- `codeAction/resolve` -local function on_code_action_results(results, ctx, options) - local action_tuples = {} - +---@param results table +---@param opts? vim.lsp.buf.code_action.opts +local function on_code_action_results(results, opts) + ---@param a lsp.Command|lsp.CodeAction local function action_filter(a) -- filter by specified action kind - if options and options.context and options.context.only then + if opts and opts.context and opts.context.only then if not a.kind then return false end local found = false - for _, o in ipairs(options.context.only) do + for _, o in ipairs(opts.context.only) do -- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate' -- this filter allows both 'type-annotate' and 'type-annotate.foo', for example if a.kind == o or vim.startswith(a.kind, o .. '.') then @@ -610,26 +622,31 @@ local function on_code_action_results(results, ctx, options) end end -- filter by user function - if options and options.filter and not options.filter(a) then + if opts and opts.filter and not opts.filter(a) then return false end -- no filter removed this action return true end - for client_id, result in pairs(results) do + ---@type {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}[] + local actions = {} + for _, result in pairs(results) do for _, action in pairs(result.result or {}) do if action_filter(action) then - table.insert(action_tuples, { client_id, action }) + table.insert(actions, { action = action, ctx = result.ctx }) end end end - if #action_tuples == 0 then + if #actions == 0 then vim.notify('No code actions available', vim.log.levels.INFO) return end - local function apply_action(action, client) + ---@param action lsp.Command|lsp.CodeAction + ---@param client lsp.Client + ---@param ctx lsp.HandlerContext + local function apply_action(action, client, ctx) if action.edit then util.apply_workspace_edit(action.edit, client.offset_encoding) end @@ -639,8 +656,9 @@ local function on_code_action_results(results, ctx, options) end end - local function on_user_choice(action_tuple) - if not action_tuple then + ---@param choice {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext} + local function on_user_choice(choice) + if not choice then return end -- textDocument/codeAction can return either Command[] or CodeAction[] @@ -656,10 +674,11 @@ local function on_code_action_results(results, ctx, options) -- arguments?: any[] -- ---@type lsp.Client - local client = assert(vim.lsp.get_client_by_id(action_tuple[1])) - local action = action_tuple[2] + local client = assert(vim.lsp.get_client_by_id(choice.ctx.client_id)) + local action = choice.action + local bufnr = assert(choice.ctx.bufnr, 'Must have buffer number') - local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = ctx.bufnr }) + local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = bufnr }) local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') or client.supports_method(ms.codeAction_resolve) @@ -668,44 +687,37 @@ local function on_code_action_results(results, ctx, options) client.request(ms.codeAction_resolve, action, function(err, resolved_action) if err then if action.command then - apply_action(action, client) + apply_action(action, client, choice.ctx) else vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) end else - apply_action(resolved_action, client) + apply_action(resolved_action, client, choice.ctx) end - end, ctx.bufnr) + end, bufnr) else - apply_action(action, client) + apply_action(action, client, choice.ctx) end end -- If options.apply is given, and there are just one remaining code action, -- apply it directly without querying the user. - if options and options.apply and #action_tuples == 1 then - on_user_choice(action_tuples[1]) + if opts and opts.apply and #actions == 1 then + on_user_choice(actions[1]) return end - vim.ui.select(action_tuples, { + ---@param item {action: lsp.Command|lsp.CodeAction} + local function format_item(item) + local title = item.action.title:gsub('\r\n', '\\r\\n') + return title:gsub('\n', '\\n') + end + local select_opts = { prompt = 'Code actions:', kind = 'codeaction', - format_item = function(action_tuple) - local title = action_tuple[2].title:gsub('\r\n', '\\r\\n') - return title:gsub('\n', '\\n') - end, - }, on_user_choice) -end - ---- Requests code actions from all clients and calls the handler exactly once ---- with all aggregated results -local function code_action_request(params, options) - local bufnr = api.nvim_get_current_buf() - vim.lsp.buf_request_all(bufnr, ms.textDocument_codeAction, params, function(results) - local ctx = { bufnr = bufnr, method = ms.textDocument_codeAction, params = params } - on_code_action_results(results, ctx, options) - end) + format_item = format_item, + } + vim.ui.select(actions, select_opts, on_user_choice) end --- Selects a code action available at the current @@ -752,21 +764,50 @@ function M.code_action(options) local bufnr = api.nvim_get_current_buf() context.diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr) end - local params local mode = api.nvim_get_mode().mode - if options.range then - assert(type(options.range) == 'table', 'code_action range must be a table') - local start = assert(options.range.start, 'range must have a `start` property') - local end_ = assert(options.range['end'], 'range must have a `end` property') - params = util.make_given_range_params(start, end_) - elseif mode == 'v' or mode == 'V' then - local range = range_from_selection(0, mode) - params = util.make_given_range_params(range.start, range['end']) - else - params = util.make_range_params() + local bufnr = api.nvim_get_current_buf() + local win = api.nvim_get_current_win() + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_codeAction }) + local remaining = #clients + if remaining == 0 then + if next(vim.lsp.get_clients({ bufnr = bufnr })) then + vim.notify(vim.lsp._unsupported_method(ms.textDocument_codeAction), vim.log.levels.WARN) + end + return + end + + ---@type table + local results = {} + + ---@param err? lsp.ResponseError + ---@param result? (lsp.Command|lsp.CodeAction)[] + ---@param ctx lsp.HandlerContext + local function on_result(err, result, ctx) + results[ctx.client_id] = { error = err, result = result, ctx = ctx } + remaining = remaining - 1 + if remaining == 0 then + on_code_action_results(results, options) + end + end + + for _, client in ipairs(clients) do + ---@type lsp.CodeActionParams + local params + if options.range then + assert(type(options.range) == 'table', 'code_action range must be a table') + local start = assert(options.range.start, 'range must have a `start` property') + local end_ = assert(options.range['end'], 'range must have a `end` property') + params = util.make_given_range_params(start, end_, bufnr, client.offset_encoding) + elseif mode == 'v' or mode == 'V' then + local range = range_from_selection(bufnr, mode) + params = + util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding) + else + params = util.make_range_params(win, client.offset_encoding) + end + params.context = context + client.request(ms.textDocument_codeAction, params, on_result, bufnr) end - params.context = context - code_action_request(params, options) end --- Executes an LSP server command. -- cgit From 448907f65d6709fa234d8366053e33311a01bdb9 Mon Sep 17 00:00:00 2001 From: LW Date: Sun, 12 Nov 2023 04:54:27 -0800 Subject: feat(lsp)!: vim.lsp.inlay_hint.get(), enable(), is_enabled() #25512 refactor!: `vim.lsp.inlay_hint()` -> `vim.lsp.inlay_hint.enable()` Problem: The LSP specification allows inlay hints to include tooltips, clickable label parts, and code actions; but Neovim provides no API to query for these. Solution: Add minimal viable extension point from which plugins can query for inlay hints in a range, in order to build functionality on top of. Possible Next Steps --- - Add `virt_text_idx` field to `vim.fn.getmousepos()` return value, for usage in mappings of ``, ``, etc --- runtime/lua/vim/lsp/inlay_hint.lua | 163 +++++++++++++++++++++++++++++-------- runtime/lua/vim/lsp/protocol.lua | 7 +- 2 files changed, 137 insertions(+), 33 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index 7b58188c53..cdda5dcc17 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -98,6 +98,107 @@ function M.on_refresh(err, _, ctx, _) return vim.NIL end +--- @class vim.lsp.inlay_hint.get.filter +--- @field bufnr integer? +--- @field range lsp.Range? +--- +--- @class vim.lsp.inlay_hint.get.ret +--- @field bufnr integer +--- @field client_id integer +--- @field inlay_hint lsp.InlayHint + +--- Get the list of inlay hints, (optionally) restricted by buffer, client, or range. +--- +--- Example usage: +--- +--- ```lua +--- local hint = vim.lsp.inlay_hint.get({ bufnr = 0 })[1] -- 0 for current buffer +--- +--- local client = vim.lsp.get_client_by_id(hint.client_id) +--- resolved_hint = client.request_sync('inlayHint/resolve', hint.inlay_hint, 100, 0).result +--- vim.lsp.util.apply_text_edits(resolved_hint.textEdits, 0, client.encoding) +--- +--- location = resolved_hint.label[1].location +--- client.request('textDocument/hover', { +--- textDocument = { uri = location.uri }, +--- position = location.range.start, +--- }) +--- ``` +--- +--- @param filter vim.lsp.inlay_hint.get.filter? +--- Optional filters |kwargs|: +--- - bufnr (integer?): 0 for current buffer +--- - range (lsp.Range?) +--- +--- @return vim.lsp.inlay_hint.get.ret[] +--- Each list item is a table with the following fields: +--- - bufnr (integer) +--- - client_id (integer) +--- - inlay_hint (lsp.InlayHint) +function M.get(filter) + vim.validate({ filter = { filter, 'table', true } }) + filter = filter or {} + + local bufnr = filter.bufnr + if not bufnr then + --- @type vim.lsp.inlay_hint.get.ret[] + local hints = {} + --- @param buf integer + vim.tbl_map(function(buf) + vim.list_extend(hints, M.get(vim.tbl_extend('keep', { bufnr = buf }, filter))) + end, vim.api.nvim_list_bufs()) + return hints + elseif bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.client_hint) then + return {} + end + + local clients = vim.lsp.get_clients({ + bufnr = bufnr, + method = ms.textDocument_inlayHint, + }) + if #clients == 0 then + return {} + end + + local range = filter.range + if not range then + range = { + start = { line = 0, character = 0 }, + ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, + } + end + + --- @type vim.lsp.inlay_hint.get.ret[] + local hints = {} + for _, client in pairs(clients) do + local hints_by_lnum = bufstate.client_hint[client.id] + if hints_by_lnum then + for lnum = range.start.line, range['end'].line do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local line, char = hint.position.line, hint.position.character + if + (line > range.start.line or char >= range.start.character) + and (line < range['end'].line or char <= range['end'].character) + then + table.insert(hints, { + bufnr = bufnr, + client_id = client.id, + inlay_hint = hint, + }) + end + end + end + end + end + return hints +end + --- Clear inlay hints ---@param bufnr (integer) Buffer handle, or 0 for current local function clear(bufnr) @@ -120,8 +221,8 @@ local function clear(bufnr) end --- Disable inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current -local function disable(bufnr) +---@param bufnr (integer|nil) Buffer handle, or 0 or nil for current +local function _disable(bufnr) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() end @@ -142,8 +243,8 @@ local function _refresh(bufnr, opts) end --- Enable inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current -local function enable(bufnr) +---@param bufnr (integer|nil) Buffer handle, or 0 or nil for current +local function _enable(bufnr) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() end @@ -175,7 +276,7 @@ local function enable(bufnr) end end, on_detach = function(_, cb_bufnr) - disable(cb_bufnr) + _disable(cb_bufnr) end, }) api.nvim_create_autocmd('LspDetach', { @@ -188,7 +289,7 @@ local function enable(bufnr) return c.id ~= args.data.client_id end) then - disable(bufnr) + _disable(bufnr) end end, group = augroup, @@ -199,20 +300,6 @@ local function enable(bufnr) end end ---- Toggle inlay hints for a buffer ----@param bufnr (integer) Buffer handle, or 0 for current -local function toggle(bufnr) - if bufnr == nil or bufnr == 0 then - bufnr = api.nvim_get_current_buf() - end - local bufstate = bufstates[bufnr] - if bufstate and bufstate.enabled then - disable(bufnr) - else - enable(bufnr) - end -end - api.nvim_set_decoration_provider(namespace, { on_win = function(_, _, bufnr, topline, botline) local bufstate = bufstates[bufnr] @@ -260,15 +347,27 @@ api.nvim_set_decoration_provider(namespace, { end, }) -return setmetatable(M, { - __call = function(_, bufnr, enable_) - vim.validate({ enable = { enable_, { 'boolean', 'nil' } }, bufnr = { bufnr, 'number' } }) - if enable_ then - enable(bufnr) - elseif enable_ == false then - disable(bufnr) - else - toggle(bufnr) - end - end, -}) +--- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current +--- @return boolean +function M.is_enabled(bufnr) + vim.validate({ bufnr = { bufnr, 'number', true } }) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + return bufstates[bufnr] and bufstates[bufnr].enabled or false +end + +--- Enable/disable/toggle inlay hints for a buffer +--- +--- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current +--- @param enable (boolean|nil) true/nil to enable, false to disable +function M.enable(bufnr, enable) + vim.validate({ enable = { enable, 'boolean', true }, bufnr = { bufnr, 'number', true } }) + if enable == false then + _disable(bufnr) + else + _enable(bufnr) + end +end + +return M diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 7a48c800c6..e2396e9a5f 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -648,7 +648,12 @@ function protocol.make_client_capabilities() inlayHint = { dynamicRegistration = true, resolveSupport = { - properties = {}, + properties = { + 'textEdits', + 'tooltip', + 'location', + 'command', + }, }, }, semanticTokens = { -- cgit From 48bcc7b9710d6db619b05254ea87f4087cdd9764 Mon Sep 17 00:00:00 2001 From: Chris Simon Date: Tue, 14 Nov 2023 05:39:43 +1100 Subject: fix(lsp): advertise workspace.didChangeConfiguration capability (#26028) This ensures workspace/didChangeConfiguration notification sent after init is correctly handled --- runtime/lua/vim/lsp/protocol.lua | 3 +++ 1 file changed, 3 insertions(+) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index e2396e9a5f..a7c3914834 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -855,6 +855,9 @@ function protocol.make_client_capabilities() }, }, configuration = true, + didChangeConfiguration = { + dynamicRegistration = false, + }, workspaceFolders = true, applyEdit = true, workspaceEdit = { -- cgit From ec79ff893d5906e1f0d90953cffa535ffae47823 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 20 Nov 2023 17:19:41 +0100 Subject: refactor(lsp): add type annotations to _watchfiles (#26109) --- runtime/lua/vim/lsp/_watchfiles.lua | 108 ++++++++++++++++++------------------ 1 file changed, 53 insertions(+), 55 deletions(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua index 1a4909b3f3..1fd112631d 100644 --- a/runtime/lua/vim/lsp/_watchfiles.lua +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -6,13 +6,11 @@ local lpeg = vim.lpeg local M = {} ----@alias lpeg userdata - --- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" --- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. --- ---@param pattern string The raw glob pattern ----@return lpeg An |lpeg| representation of the pattern, or nil if the pattern is invalid. +---@return vim.lpeg.Pattern? pattern An |lpeg| representation of the pattern, or nil if the pattern is invalid. local function parse(pattern) local l = lpeg @@ -73,36 +71,38 @@ local function parse(pattern) End = P(-1) * Cc(l.P(-1)), }) - return p:match(pattern) + return p:match(pattern) --[[@as vim.lpeg.Pattern?]] end ---@private --- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern --- ----@param pattern string|table The glob pattern (raw or parsed) to match. +---@param pattern string|vim.lpeg.Pattern The glob pattern (raw or parsed) to match. ---@param s string The string to match against pattern. ---@return boolean Whether or not pattern matches s. function M._match(pattern, s) if type(pattern) == 'string' then - pattern = parse(pattern) + local p = assert(parse(pattern)) + return p:match(s) ~= nil end return pattern:match(s) ~= nil end M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll ----@type table> client id -> registration id -> cancel function +---@type table> client id -> registration id -> cancel function local cancels = vim.defaulttable() local queue_timeout_ms = 100 ----@type table client id -> libuv timer which will send queued changes at its timeout +---@type table client id -> libuv timer which will send queued changes at its timeout local queue_timers = {} ----@type table client id -> set of queued changes to send in a single LSP notification +---@type table client id -> set of queued changes to send in a single LSP notification local change_queues = {} ----@type table> client id -> URI -> last type of change processed +---@type table> client id -> URI -> last type of change processed --- Used to prune consecutive events of the same type for the same file local change_cache = vim.defaulttable() +---@type table local to_lsp_change_type = { [watch.FileChangeType.Created] = protocol.FileChangeType.Created, [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, @@ -111,18 +111,18 @@ local to_lsp_change_type = { --- Default excludes the same as VSCode's `files.watcherExclude` setting. --- https://github.com/microsoft/vscode/blob/eef30e7165e19b33daa1e15e92fa34ff4a5df0d3/src/vs/workbench/contrib/files/browser/files.contribution.ts#L261 ----@type lpeg parsed Lpeg pattern +---@type vim.lpeg.Pattern parsed Lpeg pattern M._poll_exclude_pattern = parse('**/.git/{objects,subtree-cache}/**') + parse('**/node_modules/*/**') + parse('**/.hg/store/**') --- Registers the workspace/didChangeWatchedFiles capability dynamically. --- ----@param reg table LSP Registration object. ----@param ctx table Context from the |lsp-handler|. +---@param reg lsp.Registration LSP Registration object. +---@param ctx lsp.HandlerContext Context from the |lsp-handler|. function M.register(reg, ctx) local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) + local client = assert(vim.lsp.get_client_by_id(client_id), 'Client must be running') -- Ill-behaved servers may not honor the client capability and try to register -- anyway, so ignore requests when the user has opted out of the feature. local has_capability = vim.tbl_get( @@ -134,57 +134,53 @@ function M.register(reg, ctx) if not has_capability or not client.workspace_folders then return end - local watch_regs = {} --- @type table - for _, w in ipairs(reg.registerOptions.watchers) do - local relative_pattern = false - local glob_patterns = {} --- @type {baseUri:string, pattern: string}[] - if type(w.globPattern) == 'string' then + local register_options = reg.registerOptions --[[@as lsp.DidChangeWatchedFilesRegistrationOptions]] + ---@type table by base_dir + local watch_regs = vim.defaulttable() + for _, w in ipairs(register_options.watchers) do + local kind = w.kind + or (protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete) + local glob_pattern = w.globPattern + + if type(glob_pattern) == 'string' then + local pattern = parse(glob_pattern) + if not pattern then + error('Cannot parse pattern: ' .. glob_pattern) + end for _, folder in ipairs(client.workspace_folders) do - table.insert(glob_patterns, { baseUri = folder.uri, pattern = w.globPattern }) + local base_dir = vim.uri_to_fname(folder.uri) + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind }) end else - relative_pattern = true - table.insert(glob_patterns, w.globPattern) - end - for _, glob_pattern in ipairs(glob_patterns) do - local base_dir = nil ---@type string? - if type(glob_pattern.baseUri) == 'string' then - base_dir = glob_pattern.baseUri - elseif type(glob_pattern.baseUri) == 'table' then - base_dir = glob_pattern.baseUri.uri - end - assert(base_dir, "couldn't identify root of watch") - base_dir = vim.uri_to_fname(base_dir) - - ---@type integer - local kind = w.kind - or protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete - + local base_uri = glob_pattern.baseUri + local uri = type(base_uri) == 'string' and base_uri or base_uri.uri + local base_dir = vim.uri_to_fname(uri) local pattern = parse(glob_pattern.pattern) - assert(pattern, 'invalid pattern: ' .. glob_pattern.pattern) - if relative_pattern then - pattern = lpeg.P(base_dir .. '/') * pattern + if not pattern then + error('Cannot parse pattern: ' .. glob_pattern.pattern) end - - watch_regs[base_dir] = watch_regs[base_dir] or {} - table.insert(watch_regs[base_dir], { - pattern = pattern, - kind = kind, - }) + pattern = lpeg.P(base_dir .. '/') * pattern + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind }) end end + ---@param base_dir string local callback = function(base_dir) return function(fullpath, change_type) - for _, w in ipairs(watch_regs[base_dir]) do - change_type = to_lsp_change_type[change_type] + local registrations = watch_regs[base_dir] + for _, w in ipairs(registrations) do + local lsp_change_type = assert( + to_lsp_change_type[change_type], + 'Must receive change type Created, Changed or Deleted' + ) -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) - local kind_mask = bit.lshift(1, change_type - 1) + local kind_mask = bit.lshift(1, lsp_change_type - 1) local change_type_match = bit.band(w.kind, kind_mask) == kind_mask - if M._match(w.pattern, fullpath) and change_type_match then + if w.pattern:match(fullpath) ~= nil and change_type_match then + ---@type lsp.FileEvent local change = { uri = vim.uri_from_fname(fullpath), - type = change_type, + type = lsp_change_type, } local last_type = change_cache[client_id][change.uri] @@ -196,9 +192,11 @@ function M.register(reg, ctx) if not queue_timers[client_id] then queue_timers[client_id] = vim.defer_fn(function() - client.notify(ms.workspace_didChangeWatchedFiles, { + ---@type lsp.DidChangeWatchedFilesParams + local params = { changes = change_queues[client_id], - }) + } + client.notify(ms.workspace_didChangeWatchedFiles, params) queue_timers[client_id] = nil change_queues[client_id] = nil change_cache[client_id] = nil @@ -235,8 +233,8 @@ end --- Unregisters the workspace/didChangeWatchedFiles capability dynamically. --- ----@param unreg table LSP Unregistration object. ----@param ctx table Context from the |lsp-handler|. +---@param unreg lsp.Unregistration LSP Unregistration object. +---@param ctx lsp.HandlerContext Context from the |lsp-handler|. function M.unregister(unreg, ctx) local client_id = ctx.client_id local client_cancels = cancels[client_id] -- cgit From 9fa9b3cad94a1ea7fced128fed2cd5ac3ff7bc44 Mon Sep 17 00:00:00 2001 From: LW Date: Mon, 27 Nov 2023 08:23:04 -0800 Subject: docs: support @since for api level #25574 close #25416 --- runtime/lua/vim/lsp/inlay_hint.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/lsp') diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua index cdda5dcc17..4f7a3b0076 100644 --- a/runtime/lua/vim/lsp/inlay_hint.lua +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -107,7 +107,7 @@ end --- @field client_id integer --- @field inlay_hint lsp.InlayHint ---- Get the list of inlay hints, (optionally) restricted by buffer, client, or range. +--- Get the list of inlay hints, (optionally) restricted by buffer or range. --- --- Example usage: --- @@ -135,6 +135,8 @@ end --- - bufnr (integer) --- - client_id (integer) --- - inlay_hint (lsp.InlayHint) +--- +--- @since 12 function M.get(filter) vim.validate({ filter = { filter, 'table', true } }) filter = filter or {} @@ -349,6 +351,7 @@ api.nvim_set_decoration_provider(namespace, { --- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current --- @return boolean +--- @since 12 function M.is_enabled(bufnr) vim.validate({ bufnr = { bufnr, 'number', true } }) if bufnr == nil or bufnr == 0 then @@ -361,6 +364,7 @@ end --- --- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current --- @param enable (boolean|nil) true/nil to enable, false to disable +--- @since 12 function M.enable(bufnr, enable) vim.validate({ enable = { enable, 'boolean', true }, bufnr = { bufnr, 'number', true } }) if enable == false then -- cgit