diff options
author | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 21:52:58 +0000 |
---|---|---|
committer | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 21:52:58 +0000 |
commit | 931bffbda3668ddc609fc1da8f9eb576b170aa52 (patch) | |
tree | d8c1843a95da5ea0bb4acc09f7e37843d9995c86 /runtime/lua/vim/lsp | |
parent | 142d9041391780ac15b89886a54015fdc5c73995 (diff) | |
parent | 4a8bf24ac690004aedf5540fa440e788459e5e34 (diff) | |
download | rneovim-userreg.tar.gz rneovim-userreg.tar.bz2 rneovim-userreg.zip |
Merge remote-tracking branch 'upstream/master' into userreguserreg
Diffstat (limited to 'runtime/lua/vim/lsp')
-rw-r--r-- | runtime/lua/vim/lsp/_completion.lua | 236 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_dynamic.lua | 109 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_meta.lua | 22 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_meta/protocol.lua | 4396 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_snippet.lua | 500 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_snippet_grammar.lua | 181 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/_watchfiles.lua | 251 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/buf.lua | 380 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/codelens.lua | 122 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/diagnostic.lua | 285 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/handlers.lua | 321 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/health.lua | 19 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/inlay_hint.lua | 377 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/log.lua | 30 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/protocol.lua | 594 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/rpc.lua | 230 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/semantic_tokens.lua | 325 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/sync.lua | 25 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/tagfunc.lua | 46 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/util.lua | 834 |
20 files changed, 7520 insertions, 1763 deletions
diff --git a/runtime/lua/vim/lsp/_completion.lua b/runtime/lua/vim/lsp/_completion.lua new file mode 100644 index 0000000000..7a607d6c13 --- /dev/null +++ b/runtime/lua/vim/lsp/_completion.lua @@ -0,0 +1,236 @@ +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 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 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 + +---@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, + cursor_col, + 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, cursor_col) + 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 + if remaining == 0 then + return findstart == 1 and -1 or {} + end + + local win = api.nvim_get_current_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, cursor_col) + local client_start_boundary = vim.fn.match(line_to_cursor, '\\k*$') --[[@as integer]] + local server_start_boundary = nil + local items = {} + + local function on_done() + local mode = api.nvim_get_mode()['mode'] + if mode == 'i' or mode == 'ic' then + vim.fn.complete((server_start_boundary or client_start_boundary) + 1, 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 + require('vim.lsp.log').warn(err.message) + end + if result and vim.fn.mode() == 'i' then + local matches + matches, server_start_boundary = M._convert_results( + line, + lnum, + cursor_col, + client_start_boundary, + server_start_boundary, + result, + client.offset_encoding + ) + 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/_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<string, lsp.Registration[]> +--- @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/_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<string, lsp.LSPAny> +---@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<lsp.DocumentUri, lsp.TextEdit[]> +---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<lsp.ChangeAnnotationIdentifier, lsp.ChangeAnnotation> + +---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<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---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<cursor position>` 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<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---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<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---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<string, lsp.LSPAny> + +---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/_snippet.lua b/runtime/lua/vim/lsp/_snippet.lua deleted file mode 100644 index 3488639fb4..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.tbl_contains(targets, c) and not vim.tbl_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 - 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<string, number> -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/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua new file mode 100644 index 0000000000..9318fefcbc --- /dev/null +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -0,0 +1,181 @@ +--- 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 +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') + +-- 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 +--- @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 + end) + return escaped + end +end + +--- 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(text(escapable .. ',|') ^ 1) / escape_text(escapable .. ',|') + +-- Within format nodes, make sure we stop at / +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(text(escapable, escapable .. ':') ^ 1) / escape_text(), 'if_text') + +-- Matches the string inside //, allowing escaping of the closing slash. +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') + +--- @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<T>: { type: vim.snippet.Type, data: T } +--- @class vim.snippet.TabstopData: { tabstop: integer } +--- @class vim.snippet.TextData: { text: string } +--- @class vim.snippet.PlaceholderData: { tabstop: integer, value: vim.snippet.Node<any> } +--- @class vim.snippet.ChoiceData: { tabstop: integer, values: string[] } +--- @class vim.snippet.VariableData: { name: string, default?: vim.snippet.Node<any>, regex?: string, format?: vim.snippet.Node<vim.snippet.FormatData|vim.snippet.TextData>[], options?: string } +--- @class vim.snippet.FormatData: { capture: number, modifier?: string, if_text?: string, else_text?: string } +--- @class vim.snippet.SnippetData: { children: vim.snippet.Node<any>[] } + +--- @type vim.snippet.Node<any> +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 +--- @param type vim.snippet.Type +--- @return fun(data: T): vim.snippet.Node<T> +local function node(type) + return function(data) + return setmetatable({ type = type, data = data }, Node) + end +end + +-- stylua: ignore +local G = P({ + 'snippet'; + snippet = Ct(Cg( + Ct(( + V('any') + + (Ct(Cg((text(escapable, '$') ^ 1) / escape_text(), 'text')) / node(Type.Text)) + ) ^ 1), 'children' + ) * -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 * + 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<vim.snippet.SnippetData> +function M.parse(input) + local snippet = G:match(input) + assert(snippet, 'snippet parsing failed') + return snippet --- @type vim.snippet.Node<vim.snippet.SnippetData> +end + +return M diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua new file mode 100644 index 0000000000..1fd112631d --- /dev/null +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -0,0 +1,251 @@ +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 = {} + +--- 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 vim.lpeg.Pattern? pattern An |lpeg| representation of the pattern, or nil if the pattern is invalid. +local function parse(pattern) + local l = lpeg + + local P, S, V = lpeg.P, lpeg.S, lpeg.V + local C, Cc, Ct, Cf = lpeg.C, lpeg.Cc, lpeg.Ct, lpeg.Cf + + local pathsep = '/' + + local function class(inv, ranges) + for i, r in ipairs(ranges) do + ranges[i] = r[1] .. r[2] + end + local patt = l.R(unpack(ranges)) + if inv == '!' then + patt = P(1) - patt + end + return patt + end + + local function add(acc, a) + return acc + a + end + + local function mul(acc, m) + return acc * m + end + + local function star(stars, after) + return (-after * (l.P(1) - pathsep)) ^ #stars * after + end + + 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) --[[@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|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 + 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<integer, table<string, function[]>> client id -> registration id -> cancel function +local cancels = vim.defaulttable() + +local queue_timeout_ms = 100 +---@type table<integer, uv.uv_timer_t> client id -> libuv timer which will send queued changes at its timeout +local queue_timers = {} +---@type table<integer, lsp.FileEvent[]> client id -> set of queued changes to send in a single LSP notification +local change_queues = {} +---@type table<integer, table<string, lsp.FileChangeType>> 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<vim._watch.FileChangeType, lsp.FileChangeType> +local to_lsp_change_type = { + [watch.FileChangeType.Created] = protocol.FileChangeType.Created, + [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, + [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 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 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 = 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( + client.config.capabilities or {}, + 'workspace', + 'didChangeWatchedFiles', + 'dynamicRegistration' + ) + if not has_capability or not client.workspace_folders then + return + end + local register_options = reg.registerOptions --[[@as lsp.DidChangeWatchedFilesRegistrationOptions]] + ---@type table<string, {pattern: vim.lpeg.Pattern, kind: lsp.WatchKind}[]> 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 + local base_dir = vim.uri_to_fname(folder.uri) + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind }) + end + else + 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) + if not pattern then + error('Cannot parse pattern: ' .. glob_pattern.pattern) + end + 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) + 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, lsp_change_type - 1) + local change_type_match = bit.band(w.kind, kind_mask) == kind_mask + if w.pattern:match(fullpath) ~= nil and change_type_match then + ---@type lsp.FileEvent + local change = { + uri = vim.uri_from_fname(fullpath), + type = lsp_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() + ---@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 + end, queue_timeout_ms) + end + + break -- if an event matches multiple watchers, only send one notification + end + end + end + 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 + +--- Unregisters the workspace/didChangeWatchedFiles capability dynamically. +--- +---@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] + 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/buf.lua b/runtime/lua/vim/lsp/buf.lua index 6ac885c78f..cf9acc0808 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -2,10 +2,10 @@ 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 = {} ----@private --- Sends an async request to all active clients attached to the current --- buffer. --- @@ -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<integer, integer> 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,8 +31,10 @@ 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') return not not vim.lsp.buf_notify(0, 'window/progress', {}) end @@ -39,10 +42,9 @@ 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 ----@private local function request_with_options(name, params, options) local req_handler if options then @@ -60,66 +62,71 @@ 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('textDocument/declaration', params, options) + request_with_options(ms.textDocument_declaration, params, options) end --- Jumps to the definition of the symbol under the cursor. --- ---@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('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. --- ---@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('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 --- 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('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 --- 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) --- ----@see vim.lsp.protocol.constants.CompletionTriggerKind +---@see vim.lsp.protocol.CompletionTriggerKind 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 ----@private ----@return table {start={row, col}, end={row, col}} using (1, 0) indexing -local function range_from_selection() +---@param bufnr integer +---@param mode "v"|"V" +---@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 -- [bufnum, lnum, col, off]; both row and column 1-indexed @@ -138,6 +145,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 }, @@ -150,8 +162,8 @@ 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. ---- See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions +--- automatically derived from the current Nvim options. +--- 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): @@ -160,13 +172,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: ---- ---- <pre>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: <pre>lua +--- -- Never request typescript-language-server for formatting +--- vim.lsp.buf.format { +--- filter = function(client) return client.name ~= "tsserver" end +--- } --- </pre> --- --- - async boolean|nil @@ -180,39 +190,34 @@ 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 function M.format(options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local clients = vim.lsp.get_active_clients({ + 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(bufnr, mode) + end + local method = range and ms.textDocument_rangeFormatting or ms.textDocument_formatting + + local clients = vim.lsp.get_clients({ id = options.id, bufnr = bufnr, name = options.name, + method = method, }) - if options.filter then clients = vim.tbl_filter(options.filter, clients) end - 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() - end - local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' - - clients = vim.tbl_filter(function(client) - return client.supports_method(method) - end, clients) - if #clients == 0 then vim.notify('[LSP] Format request failed, no matching language servers.') end - ---@private local function set_range(client, params) if range then local range_params = @@ -264,19 +269,16 @@ 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 + method = ms.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 @@ -286,7 +288,6 @@ function M.rename(new_name, options) -- Compute early to account for cursor movements after going async local cword = vim.fn.expand('<cword>') - ---@private local function get_text_at_range(range, offset_encoding) return api.nvim_buf_get_text( bufnr, @@ -304,21 +305,20 @@ 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 - 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)) @@ -357,7 +357,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 @@ -393,7 +393,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. @@ -402,10 +402,9 @@ 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 ----@private local function pick_call_hierarchy_item(call_hierarchy_items) if not call_hierarchy_items then return @@ -425,10 +424,9 @@ 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) + request(ms.textDocument_prepareCallHierarchy, params, function(err, result, ctx) if err then vim.notify(err.message, vim.log.levels.WARN) return @@ -450,21 +448,21 @@ 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. --- 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 @@ -485,11 +483,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_active_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 @@ -499,11 +499,11 @@ function M.add_workspace_folder(workspace_folder) end end if not found then - vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) + client.notify(ms.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 @@ -518,14 +518,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_active_clients({ bufnr = 0 })) 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(ms.workspace_didChangeWorkspaceFolders, params) client.workspace_folders[idx] = nil return end @@ -540,7 +542,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) @@ -549,17 +551,18 @@ 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 --- text document position. This request can be triggered by a key mapping or --- by events such as `CursorHold`, e.g.: ---- <pre>vim ---- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() ---- </pre> +--- +--- ```vim +--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorMoved <buffer> 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. @@ -568,17 +571,25 @@ 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. ---- function M.clear_references() util.buf_clear_references() end ----@private --- +---@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,21 +598,21 @@ 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 = {} - - ---@private +---@param results table<integer, vim.lsp.CodeActionResultEntry> +---@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 - -- 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 + 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 found = true break end @@ -611,53 +622,43 @@ 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 - ---@private - 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 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 - ---@private - 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[] @@ -672,52 +673,51 @@ local function on_code_action_results(results, ctx, options) -- command: string -- arguments?: any[] -- - 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 - client.request('codeAction/resolve', action, function(err, resolved_action) + ---@type lsp.Client + 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 = bufnr }) + + local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') + or client.supports_method(ms.codeAction_resolve) + + 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, choice.ctx) + else + vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) + end + else + apply_action(resolved_action, client, choice.ctx) end - apply_action(resolved_action, client) - end) + 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 ----@private -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 } - 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 @@ -743,11 +743,11 @@ 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 ----@see vim.lsp.protocol.constants.CodeActionTriggerKind +---@see vim.lsp.protocol.CodeActionTriggerKind function M.code_action(options) validate({ options = { options, 't', true } }) options = options or {} @@ -764,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() - 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<integer, vim.lsp.CodeActionResultEntry> + 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. @@ -795,8 +824,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 --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 17489ed84d..9cccaa1d66 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 = {} @@ -7,6 +8,7 @@ local M = {} --- to throttle refreshes to at most one at a time local active_refreshes = {} +---@type table<integer, table<integer, lsp.CodeLens[]>> --- bufnr -> client_id -> lenses local lens_cache_by_buf = setmetatable({}, { __index = function(t, b) @@ -15,6 +17,8 @@ local lens_cache_by_buf = setmetatable({}, { end, }) +---@type table<integer, integer> +---client_id -> namespace local namespaces = setmetatable({}, { __index = function(t, key) local value = api.nvim_create_namespace('vim_lsp_codelens:' .. key) @@ -26,43 +30,34 @@ local namespaces = setmetatable({}, { ---@private M.__namespaces = namespaces ----@private +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) 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.tbl_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(...) - local result = vim.lsp.handlers['workspace/executeCommand'](...) + client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) + vim.lsp.handlers[ms.workspace_executeCommand](...) M.refresh() - return result - end, bufnr) + end) end --- Return all lenses for the given buffer --- ----@param bufnr number Buffer number. 0 can be used for the current buffer. ----@return table (`CodeLens[]`) +---@param bufnr integer Buffer number. 0 can be used for the current buffer. +---@return lsp.CodeLens[] function M.get(bufnr) local lenses_by_client = lens_cache_by_buf[bufnr or 0] if not lenses_by_client then @@ -97,6 +92,7 @@ function M.run() else vim.ui.select(options, { prompt = 'Code lenses:', + kind = 'codelens', format_item = function(option) return option.lens.command.title end, @@ -108,22 +104,26 @@ function M.run() end end ----@private local function resolve_bufnr(bufnr) return bufnr == 0 and api.nvim_get_current_buf() or bufnr 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) + 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 @@ -131,16 +131,21 @@ end --- Display the lenses using virtual text --- ----@param lenses table of lenses to display (`CodeLens[] | null`) ----@param bufnr number ----@param client_id number +---@param lenses? lsp.CodeLens[] lenses to display +---@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) return end - local lenses_by_lnum = {} + + local lenses_by_lnum = {} ---@type table<integer, lsp.CodeLens[]> for _, lens in pairs(lenses) do local line_lenses = lenses_by_lnum[lens.range.start.line] if not line_lenses then @@ -176,17 +181,21 @@ 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 lenses? lsp.CodeLens[] lenses to store +---@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 = {} 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) @@ -197,7 +206,10 @@ function M.save(lenses, bufnr, client_id) lenses_by_client[client_id] = lenses end ----@private +---@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) @@ -206,7 +218,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 @@ -220,19 +231,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 @@ -264,10 +280,10 @@ end --- It is recommended to trigger this using an autocmd or via keymap. --- --- Example: ---- <pre>vim ---- autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() ---- </pre> --- +--- ```vim +--- autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() +--- ``` function M.refresh() local params = { textDocument = util.make_text_document_params(), @@ -277,7 +293,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 5e2bf75f1b..b6f0cfa0b3 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -1,18 +1,18 @@ ---@brief lsp-diagnostic ---- ----@class Diagnostic ----@field range Range ----@field message string ----@field severity DiagnosticSeverity|nil ----@field code number | string ----@field source string ----@field tags DiagnosticTag[] ----@field relatedInformation DiagnosticRelatedInformation[] + +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 local M = {} +local augroup = api.nvim_create_augroup('vim_lsp_diagnostic', {}) + local DEFAULT_CLIENT_ID = -1 ----@private + local function get_client_id(client_id) if client_id == nil then client_id = DEFAULT_CLIENT_ID @@ -21,15 +21,15 @@ 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 - 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] @@ -37,7 +37,7 @@ 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 return col @@ -52,7 +52,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) @@ -77,12 +76,36 @@ 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 + log.info(string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id)) + end + end + return tags +end + +---@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 +117,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 +131,12 @@ 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) + ---@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,26 +157,53 @@ local function diagnostic_vim_to_lsp(diagnostics) end, diagnostics) end -local _client_namespaces = {} +---@type table<integer, integer> +local _client_push_namespaces = {} + +---@type table<string, integer> +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 number The id of the LSP client -function M.get_namespace(client_id) +---@param client_id integer The id of the LSP 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' } }) - if not _client_namespaces[client_id] then - local client = vim.lsp.get_client_by_id(client_id) + + local client = vim.lsp.get_client_by_id(client_id) + if is_pull then + 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 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 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 _client_namespaces[client_id] end --- |lsp-handler| for the method "textDocument/publishDiagnostics" --- --- See |vim.diagnostic.config()| for configuration options. Handler-specific --- configuration can be set using |vim.lsp.with()|: ---- <pre>lua +--- +--- ```lua --- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( --- vim.lsp.diagnostic.on_publish_diagnostics, { --- -- Enable underline, use default values @@ -168,7 +221,7 @@ end --- update_in_insert = false, --- } --- ) ---- </pre> +--- ``` --- ---@param config table Configuration table (see |vim.diagnostic.config()|). function M.on_publish_diagnostics(_, result, ctx, config) @@ -186,7 +239,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 @@ -206,13 +259,82 @@ 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 --- 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) @@ -220,7 +342,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 @@ -232,14 +354,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 @@ -252,7 +374,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 @@ -264,4 +386,95 @@ 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 + +---@class lsp.diagnostic.bufstate +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table<integer, lsp.diagnostic.bufstate> +local bufstates = {} + +--- Disable pull diagnostics for a buffer +--- @private +local function disable(bufnr) + local bufstate = bufstates[bufnr] + if bufstate then + bufstate.enabled = false + end + 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 +function M._enable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + if not bufstates[bufnr] then + bufstates[bufnr] = { enabled = true } + + api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen + then + return + end + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr, { only_visible = true, client_id = opts.data.client_id }) + end + end, + group = augroup, + }) + + api.nvim_buf_attach(bufnr, false, { + on_reload = function() + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr) + end + end, + on_detach = function() + disable(bufnr) + end, + }) + + api.nvim_create_autocmd('LspDetach', { + buffer = 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, + }) + else + bufstates[bufnr].enabled = true + end +end + return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 5096100a60..6fde55cf04 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 @@ -7,82 +8,70 @@ local M = {} -- FIXME: DOC: Expose in vimdocs ----@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') 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 ----@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[ms.dollar_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 -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) +---@param result lsp.WorkDoneProgressCreateParams +---@param ctx lsp.HandlerContext +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[', 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 --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 @@ -117,20 +106,52 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, _, ctx) +M[ms.client_registerCapability] = function(_, result, 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' + ---@type lsp.Client 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) + + client.dynamic_capabilities:register(result.registrations) + for bufnr, _ in pairs(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 == 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 + end + end + if #unsupported > 0 then + local warning_tpl = 'The language server %s triggers a registerCapability ' + .. 'handler for %s despite dynamicRegistration set to false. ' + .. 'Report upstream, this warning is harmless' + local client_name = client and client.name or string.format('id=%d', client_id) + local warning = string.format(warning_tpl, client_name, table.concat(unsupported, ', ')) + log.warn(warning) + end + return vim.NIL +end + +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability +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 == ms.workspace_didChangeWatchedFiles then + require('vim.lsp._watchfiles').unregister(unreg, ctx) + end + end return vim.NIL 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' @@ -150,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 @@ -180,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 @@ -190,16 +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/codeLens'] = function(...) +M[ms.textDocument_diagnostic] = function(...) + return require('vim.lsp.diagnostic').on_diagnostic(...) +end + +M[ms.textDocument_codeLens] = function(...) return require('vim.lsp.codelens').on_codelens(...) end +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 @@ -221,7 +250,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 @@ -256,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) @@ -266,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 @@ -281,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 @@ -290,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 @@ -299,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 @@ -314,20 +342,22 @@ M['textDocument/completion'] = function(_, result, _, _) end --- |lsp-handler| for the method "textDocument/hover" ---- <pre>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" ---- } ---- ) ---- </pre> +--- +--- ```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 ---- - 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 @@ -341,21 +371,28 @@ 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 - vim.notify('No information available') + local format = 'markdown' + local contents ---@type string[] + if type(result.contents) == 'table' and result.contents.kind == 'plaintext' then + format = 'plaintext' + contents = vim.split(result.contents.value or '', '\n', { trimempty = true }) + else + contents = util.convert_input_to_markdown_lines(result.contents) + end + 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 -M['textDocument/hover'] = M.hover +M[ms.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[]` @@ -370,50 +407,54 @@ 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 -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|. ---- <pre>lua ---- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( ---- vim.lsp.handlers.signature_help, { ---- -- Use a sharp border with `FloatBorder` highlights ---- border = "single" ---- } ---- ) ---- </pre> +--- +--- ```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 ---- - 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 @@ -432,10 +473,9 @@ 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 + if not lines or vim.tbl_isempty(lines) then if config.silent ~= true then print('No signature help available') end @@ -443,16 +483,18 @@ 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 --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 @@ -469,8 +511,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 @@ -494,13 +537,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 @@ -522,7 +565,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 @@ -541,27 +584,19 @@ 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 -- 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, err = vim.ui.open(uri) - local ret = vim.fn.system(cmd) - if vim.v.shell_error ~= 0 then + if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret, + message = ret and ret.stderr or err, }, } end @@ -573,7 +608,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 @@ -589,6 +624,11 @@ M['window/showDocument'] = function(_, result, ctx, _) return { success = success or false } end +---@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 + -- Add boilerplate error validation and logging for all of these. for k, fn in pairs(M) do M[k] = function(err, result, ctx, config) @@ -622,4 +662,3 @@ for k, fn in pairs(M) do end return M --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 987707e661..fe06006108 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() @@ -22,18 +22,25 @@ 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) 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') + local clients = vim.lsp.get_clients() + 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 diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua new file mode 100644 index 0000000000..4f7a3b0076 --- /dev/null +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -0,0 +1,377 @@ +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 = {} + +---@class lsp.inlay_hint.bufstate +---@field version? integer +---@field client_hint? table<integer, table<integer, lsp.InlayHint[]>> client_id -> (lnum -> hints) +---@field applied table<integer, integer> Last version of hints applied to this line +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table<integer, lsp.inlay_hint.bufstate> +local bufstates = {} + +local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') +local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) + +--- |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 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 + 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) + 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 + +--- |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 + local bufstate = bufstates[bufnr] + if bufstate then + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) + break + end + end + end + end + + 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 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) +--- +--- @since 12 +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) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + if not bufstates[bufnr] then + return + end + 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 + +--- Disable inlay hints for a buffer +---@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 + clear(bufnr) + if bufstates[bufnr] then + bufstates[bufnr] = { enabled = false, applied = {} } + 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|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 + local bufstate = bufstates[bufnr] + if not bufstate then + bufstates[bufnr] = { applied = {}, enabled = true } + api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen + then + return + end + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr, { client_id = opts.data.client_id }) + end + end, + group = augroup, + }) + _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 = {} + _refresh(cb_bufnr) + end + end, + on_detach = function(_, cb_bufnr) + _disable(cb_bufnr) + end, + }) + api.nvim_create_autocmd('LspDetach', { + buffer = 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 + _refresh(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, + }) + end + end + bufstate.applied[lnum] = bufstate.version + end + end + end, +}) + +--- @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 + 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 +--- @since 12 +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/log.lua b/runtime/lua/vim/lsp/log.lua index d1a78572aa..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() @@ -31,8 +28,7 @@ do end end - local path_sep = vim.loop.os_uname().version:match('Windows') and '\\' or '/' - ---@private + local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/' local function path_join(...) return table.concat(vim.tbl_flatten({ ... }), path_sep) end @@ -44,13 +40,12 @@ 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 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 @@ -68,7 +63,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', @@ -141,7 +136,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 = @@ -154,7 +149,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 @@ -167,11 +162,10 @@ 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 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 12345b6c8c..a7c3914834 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -20,15 +20,8 @@ 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 = { + --- @enum lsp.DiagnosticSeverity DiagnosticSeverity = { -- Reports an error. Error = 1, @@ -40,6 +33,7 @@ local constants = { Hint = 4, }, + --- @enum lsp.DiagnosticTag DiagnosticTag = { -- Unused or unnecessary code Unnecessary = 1, @@ -60,6 +54,7 @@ local constants = { }, -- The file event type. + ---@enum lsp.FileChangeType FileChangeType = { -- The file got created. Created = 1, @@ -247,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, @@ -637,9 +633,29 @@ export interface WorkspaceClientCapabilities { --- Gets a new ClientCapabilities object describing the LSP client --- capabilities. +--- @return lsp.ClientCapabilities function protocol.make_client_capabilities() return { + general = { + positionEncodings = { + 'utf-16', + }, + }, textDocument = { + diagnostic = { + dynamicRegistration = false, + }, + inlayHint = { + dynamicRegistration = true, + resolveSupport = { + properties = { + 'textEdits', + 'tooltip', + 'location', + 'command', + }, + }, + }, semanticTokens = { dynamicRegistration = false, tokenTypes = { @@ -702,7 +718,7 @@ function protocol.make_client_capabilities() didSave = true, }, codeAction = { - dynamicRegistration = false, + dynamicRegistration = true, codeActionLiteralSupport = { codeActionKind = { @@ -719,6 +735,12 @@ function protocol.make_client_capabilities() properties = { 'edit' }, }, }, + formatting = { + dynamicRegistration = true, + }, + rangeFormatting = { + dynamicRegistration = true, + }, completion = { dynamicRegistration = false, completionItem = { @@ -726,7 +748,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, @@ -752,6 +773,7 @@ function protocol.make_client_capabilities() }, definition = { linkSupport = true, + dynamicRegistration = true, }, implementation = { linkSupport = true, @@ -760,7 +782,7 @@ function protocol.make_client_capabilities() linkSupport = true, }, hover = { - dynamicRegistration = false, + dynamicRegistration = true, contentFormat = { protocol.MarkupKind.Markdown, protocol.MarkupKind.PlainText }, }, signatureHelp = { @@ -795,7 +817,7 @@ function protocol.make_client_capabilities() hierarchicalDocumentSymbolSupport = true, }, rename = { - dynamicRegistration = false, + dynamicRegistration = true, prepareSupport = true, }, publishDiagnostics = { @@ -811,6 +833,7 @@ function protocol.make_client_capabilities() return res end)(), }, + dataSupport = true, }, callHierarchy = { dynamicRegistration = false, @@ -830,9 +853,11 @@ function protocol.make_client_capabilities() return res end)(), }, - hierarchicalWorkspaceSymbolSupport = true, }, configuration = true, + didChangeConfiguration = { + dynamicRegistration = false, + }, workspaceFolders = true, applyEdit = true, workspaceEdit = { @@ -841,6 +866,13 @@ function protocol.make_client_capabilities() semanticTokens = { refreshSupport = true, }, + didChangeWatchedFiles = { + dynamicRegistration = true, + relativePatternSupport = true, + }, + inlayHint = { + refreshSupport = true, + }, }, experimental = nil, window = { @@ -857,10 +889,9 @@ 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 +---@return table|nil Normalized table of capabilities function protocol.resolve_capabilities(server_capabilities) local TextDocumentSyncKind = protocol.TextDocumentSyncKind local textDocumentSync = server_capabilities.textDocumentSync @@ -878,7 +909,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, @@ -890,183 +922,367 @@ 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 ----@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 +-- 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', + 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. + 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', + --- 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', + --- 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', + --- 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 + --- 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 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 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', + --- 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. + --- @since 3.18.0 + --- @proposed + textDocument_rangesFormatting = 'textDocument/rangesFormatting', + --- 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 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 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 + --- 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', + --- 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', + --- 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 + --- 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', + --- 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', + --- 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', + --- @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 + --- 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', + --- 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 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', + --- 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 `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({}, { + __index = t, + __newindex = function() + error('cannot modify immutable table') + end, + }) end +protocol.Methods = freeze(protocol.Methods) 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 f1492601ff..6ab5708721 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -1,50 +1,22 @@ -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 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 end ----@private ---- Merges current process env with the given env and returns the result as ---- a list of "k=v" strings. ---- ---- <pre> ---- 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", } ---- </pre> ----@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`. --- ---@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: ', @@ -54,15 +26,14 @@ local function format_message_with_content_length(encoded_message) }) end ----@private --- 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 = {} - 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 @@ -86,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 @@ -141,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, @@ -152,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' }, }) @@ -186,10 +159,10 @@ 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) +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({ @@ -197,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 @@ -211,37 +184,41 @@ 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. --- ---@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) + return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound) 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 }) 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) - 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) @@ -270,7 +247,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 @@ -294,7 +271,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', @@ -319,9 +296,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' }, @@ -354,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 @@ -381,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) @@ -394,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 @@ -426,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) @@ -479,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 = { @@ -519,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 = {} @@ -538,9 +513,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 @@ -548,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 @@ -556,7 +531,6 @@ local function public_client(client) return result end ----@private local function merge_dispatchers(dispatchers) if dispatchers then local user_dispatchers = dispatchers @@ -588,9 +562,9 @@ end --- and port --- ---@param host string ----@param port number +---@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() @@ -625,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) @@ -650,107 +624,93 @@ 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. --- - `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 }) +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 + 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 vim.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.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) - 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 = M.create_read_loop(handle_body, nil, function(err) + client:on_error(M.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 vim.SystemObj]] 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, -} --- vim:sw=2 ts=2 et +return M diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index b1bc48dac6..a5831c0beb 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -1,46 +1,50 @@ 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 --- @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 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 ---- @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 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 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<number, STHighlighter> ----@field bufnr number ----@field augroup number augroup for buffer events ----@field debounce number milliseconds to debounce requests for new tokens +---@field active table<integer, STHighlighter> +---@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<number, STClientState> +---@field client_state table<integer, STClientState> local STHighlighter = { active = {} } ----@private -local function binary_search(tokens, line) - local lo = 1 - local hi = #tokens +--- 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. +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 @@ -50,26 +54,33 @@ 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. +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). + 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<string, boolean> 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_table[idx]] = true end + x = bit.rshift(x, 1) idx = idx + 1 end @@ -78,17 +89,40 @@ 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) +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() + 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] @@ -98,12 +132,17 @@ local function tokens_to_ranges(data, bufnr, client) 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(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) @@ -116,7 +155,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 @@ -127,7 +166,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 }) @@ -254,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' @@ -266,7 +305,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) @@ -301,11 +340,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 @@ -333,15 +370,23 @@ 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 - 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|) @@ -361,7 +406,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 @@ -378,52 +423,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', { + buffer = self.bufnr, + modeline = false, + data = { + token = token, + client_id = client_id, + }, + }) end end end @@ -452,7 +500,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) @@ -507,14 +555,15 @@ local M = {} --- delete the semanticTokensProvider table from the {server_capabilities} of --- your client in your |LspAttach| callback or your configuration's --- `on_attach` callback: ---- <pre>lua ---- client.server_capabilities.semanticTokensProvider = nil ---- </pre> --- ----@param bufnr number ----@param client_id number +--- ```lua +--- client.server_capabilities.semanticTokensProvider = nil +--- ``` +--- +---@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({ @@ -567,8 +616,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 }, @@ -590,11 +639,17 @@ 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 +---@return table|nil (table|nil) List of tokens at position. Each token has +--- the following fields: +--- - 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) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() @@ -614,7 +669,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] @@ -637,23 +692,59 @@ 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 (integer|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 (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: (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] 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` @@ -665,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/sync.lua b/runtime/lua/vim/lsp/sync.lua index 826352f036..ca01cdc08b 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,13 +86,13 @@ 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 ---@param byte integer the byte idx ---@param offset_encoding string utf-8|utf-16|utf-32|nil (default: utf-8) ----@returns table<string, int> 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 @@ -121,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 @@ -129,7 +126,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<int, int> 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, @@ -197,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. @@ -209,7 +205,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, @@ -305,12 +302,11 @@ 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 ---@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 '' @@ -341,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 @@ -388,11 +383,11 @@ 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 +---@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/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index 49029f8599..4ad50e4a58 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -1,7 +1,12 @@ local lsp = vim.lsp local util = lsp.util +local ms = lsp.protocol.Methods ----@private +---@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 @@ -9,14 +14,15 @@ 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 ----@private +---@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, 'textDocument/definition', params, 1000) + local results_by_client, err = lsp.buf_request_sync(0, ms.textDocument_definition, params, 1000) if err then return {} end @@ -24,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 @@ -42,19 +50,22 @@ local function query_definition(pattern) return results end ----@private +---@param pattern string +---@return table[] 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 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 @@ -62,14 +73,9 @@ local function query_workspace_symbols(pattern) return results end ----@private 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 diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 38051e6410..32b220746f 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1,10 +1,10 @@ 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 local highlight = require('vim.highlight') -local uv = vim.loop +local uv = vim.uv local npcall = vim.F.npcall local split = vim.split @@ -22,12 +22,11 @@ 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 +---@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 @@ -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', true) + return split(value, '\n', { plain = true, trimempty = true }) end ----@private local function create_window_without_focus() local prev = vim.api.nvim_get_current_win() vim.cmd.new() @@ -121,9 +116,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 encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ----@return number `encoding` index of `index` in `line` +---@param index integer|nil byte index (utf-8), or `nil` for length +---@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 encoding = 'utf-16' @@ -149,9 +144,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 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` +---@param index integer UTF index +---@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 encoding = 'utf-16' @@ -173,15 +168,17 @@ 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 ----@param new_lines A list of strings to replace the original ----@returns (table) The modified {lines} object +---@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 (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 @@ -219,7 +216,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,14 +230,13 @@ 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. --- ----@param bufnr number bufnr to get the lines from ----@param rows number[] zero-indexed line numbers ----@return table<number string> a table mapping rows to lines +---@param bufnr integer bufnr to get the lines from +---@param rows integer[] zero-indexed line numbers +---@return table<integer, string>|string a table mapping rows to lines local function get_lines(bufnr, rows) rows = type(rows) == 'table' and rows or { rows } @@ -250,15 +245,19 @@ local function get_lines(bufnr, rows) bufnr = api.nvim_get_current_buf() end - ---@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 +267,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 @@ -316,23 +310,20 @@ 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. --- ----@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] 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 ---- 1-indexed +---@param offset_encoding string|nil utf-8|utf-16|utf-32 +---@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 @@ -353,11 +344,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 + for _, client in ipairs(vim.lsp.get_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 @@ -386,7 +406,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) @@ -401,7 +421,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 @@ -434,25 +454,15 @@ 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 - local cursor = (function() - if not is_current_buf then - return { - row = -1, - col = -1, - } + -- 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 - local cursor = api.nvim_win_get_cursor(0) - return { - row = cursor[1] - 1, - col = cursor[2], - } - end)() + 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 @@ -464,7 +474,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) @@ -499,42 +509,28 @@ 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 local max = api.nvim_buf_line_count(bufnr) - -- 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, max - 1) or '') - if is_valid_cursor then - api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col }) + -- 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 -- 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, {}) @@ -551,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. ----@param result (table) The result of a `textDocument/completion` request ----@returns (table) List of completion items +---@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 @@ -571,7 +569,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 @@ -610,130 +608,36 @@ end --- Parses snippets in a completion entry. --- +---@deprecated ---@param input string unparsed snippet ----@returns string parsed 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 tostring(snippet.parse(input)) + return snippet.parse(input) end) if not ok then return input end - return parsed -end - ----@private ---- 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 - ----@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 -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 ----@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. -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. ---- ----@param completion_item_kind (`vim.lsp.protocol.completionItemKind`) ----@returns (`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' + return tostring(parsed) 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 ----|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, +---@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` ---@param prefix (string) the prefix to filter the completion items ----@returns { matches = complete-items table, incomplete = bool } ----@see |complete-items| +---@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 - -- TODO(ashkan) Validation handling here? - 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, - icase = 1, - dup = 1, - empty = 1, - user_data = { - nvim = { - lsp = { - completion_item = completion_item, - }, - }, - }, - }) - end - - return matches + 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 ----@private --- Like vim.fn.bufwinid except it works across tabpages. local function bufwinid(bufnr) for _, win in ipairs(api.nvim_list_wins()) do @@ -743,6 +647,19 @@ local function bufwinid(bufnr) end end +--- Get list of buffers for a directory +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,26 +672,41 @@ 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 - api.nvim_buf_call(oldbuf, function() - vim.cmd('w!') - end) + 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 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 local function create_file(change) local opts = change.options or {} -- from spec: Overwrite wins over `ignoreIfExists` @@ -789,7 +721,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) @@ -855,9 +786,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 {}. ----@returns {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 {} @@ -865,27 +799,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 <text></text> 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 <text></text> block so that stylize_markdown - -- can properly process it as plaintext - value = string.format('<text>\n%s\n</text>', 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, '```') @@ -903,12 +823,13 @@ 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 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 @@ -932,11 +853,17 @@ 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', 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 + -- 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 @@ -1007,16 +934,22 @@ 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 opts (table, optional) ---- - offset_x (number) offset to add to `col` ---- - offset_y (number) offset to add to `row` +---@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 +--- - 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({ opts = { opts, 't', true }, @@ -1034,19 +967,33 @@ 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 + + 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 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 @@ -1080,7 +1027,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. @@ -1112,7 +1059,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) @@ -1137,7 +1084,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) @@ -1157,8 +1104,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 @@ -1171,19 +1119,18 @@ 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. + -- in a valid syntax definition. -- 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' 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 @@ -1192,37 +1139,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 dictionary 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 -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 a table of lang -> syntax mappings ----@private local function get_markdown_fences() local fences = {} for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do @@ -1244,16 +1219,14 @@ 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 --- - 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 ----@returns width,height size of float +---@return table stripped content function M.stylize_markdown(bufnr, contents, opts) validate({ contents = { contents, 't' }, @@ -1264,7 +1237,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, '<pre>([a-z0-9]*)', '</pre>' }, code = { '', '<code>', '</code>' }, text = { 'text', '<text>', '</text>' }, @@ -1288,7 +1261,7 @@ function M.stylize_markdown(bufnr, contents, opts) end -- Clean up - contents = M._trim(contents, opts) + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) local stripped = {} local highlights = {} @@ -1348,6 +1321,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) @@ -1363,7 +1350,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 = {} @@ -1386,10 +1372,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 + pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) langs[lang] = true end vim.cmd( @@ -1424,15 +1410,53 @@ 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. 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[] +---@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. Carriage returns are removed + contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n', { trimempty = true }) + + -- 2. Successive empty lines are collapsed into a single empty line + contents = collapse_blank_lines(contents) + + -- 3. 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 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() -- 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 @@ -1442,13 +1466,12 @@ 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 ----@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| +---@see autocmd-events local function close_preview_autocmd(events, winnr, bufnrs) local augroup = api.nvim_create_augroup('preview_window_' .. winnr, { clear = true, @@ -1478,13 +1501,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' }, @@ -1503,7 +1527,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 @@ -1532,7 +1556,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 @@ -1553,23 +1577,22 @@ 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 +---@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 ---- - 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 --- - 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 --- - 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 ----preview window +---@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({ contents = { contents, 't' }, @@ -1578,7 +1601,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' } @@ -1610,18 +1632,23 @@ 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 + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) + 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 @@ -1636,17 +1663,18 @@ 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 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 + + vim.bo[floating_bufnr].modifiable = false + vim.bo[floating_bufnr].bufhidden = 'wipe' - api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) - api.nvim_buf_set_option(floating_bufnr, 'bufhidden', 'wipe') api.nvim_buf_set_keymap( floating_bufnr, 'n', @@ -1670,18 +1698,18 @@ do --[[ References ]] --- Removes document highlights from a buffer. --- - ---@param bufnr number Buffer id + ---@param bufnr integer|nil Buffer id function M.buf_clear_references(bufnr) - validate({ bufnr = { bufnr, 'n', true } }) + validate({ bufnr = { bufnr, { 'n' }, true } }) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) end --- 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 + ---@see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent function M.buf_highlight_references(bufnr, references, offset_encoding) validate({ bufnr = { bufnr, 'n', true }, @@ -1729,18 +1757,23 @@ 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()|. --- ---@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_clients({ bufnr = 0 })[1].offset_encoding end local items = {} @@ -1755,7 +1788,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) @@ -1787,6 +1820,7 @@ function M.locations_to_items(locations, offset_encoding) lnum = row + 1, col = col + 1, text = line, + user_data = temp.location, }) end end @@ -1802,9 +1836,8 @@ 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) for _, symbol in ipairs(_symbols) do if symbol.location then -- SymbolInformation type @@ -1842,8 +1875,9 @@ 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 +---@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) local start = 1 for i = 1, #lines do @@ -1867,8 +1901,9 @@ end --- --- CAUTION: Modifies the input in-place! --- ----@param lines (table) list of lines ----@returns (string) filetype or "markdown" if it was unchanged. +---@deprecated +---@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 @@ -1890,8 +1925,7 @@ function M.try_trim_markdown_code_blocks(lines) return 'markdown' 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 @@ -1911,9 +1945,9 @@ 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 +---@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 @@ -1926,8 +1960,8 @@ 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 ----@returns (string) encoding first client if there is one, nil otherwise +---@param bufnr (integer) buffer handle or 0 for current, defaults to current +---@return string encoding first client if there is one, nil otherwise function M._get_offset_encoding(bufnr) validate({ bufnr = { bufnr, 'n', true }, @@ -1935,7 +1969,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( @@ -1949,7 +1983,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 ) @@ -1964,9 +1998,9 @@ 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 = +---@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) @@ -1981,13 +2015,13 @@ 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 = +---@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({ @@ -2026,24 +2060,25 @@ end --- Creates a `TextDocumentIdentifier` object for the current buffer. --- ----@param bufnr number|nil: Buffer handle, defaults to current ----@returns `TextDocumentIdentifier` +---@param bufnr integer|nil: Buffer handle, defaults to current +---@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 + --- 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 +---@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 @@ -2054,7 +2089,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 } }) @@ -2070,11 +2105,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} +---@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 @@ -2082,6 +2117,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_clients({ bufnr = buf })[1].offset_encoding end -- If the col is past the EOL, use the line length. if col > #line then @@ -2092,11 +2128,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 @@ -2105,9 +2141,93 @@ 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. +--- +---@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? 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 textDocument = M.make_text_document_params(bufnr) + + local only_visible = opts.only_visible or false + + 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) + for _, client in ipairs(clients) do + client.request(method, { + textDocument = textDocument, + range = make_line_range_params(bufnr, first - 1, last - 1, client.offset_encoding), + }, nil, bufnr) + end + end + end + else + for _, client in ipairs(clients) do + 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 + M._get_line_byte_from_position = get_line_byte_from_position +---@nodoc M.buf_versions = {} return M --- vim:sw=2 ts=2 et |