This commit is contained in:
Jongwook Choi 2024-05-05 08:24:10 -07:00 committed by GitHub
commit 0a307f5d78
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 421 additions and 223 deletions

View File

@ -152,8 +152,9 @@ creating and managing clients.
The `vim.lsp.buf_…` functions perform operations for all LSP clients attached
to the given buffer. |lsp-buf|
LSP request/response handlers are implemented as Lua functions (see
|lsp-handler|).
LSP request/response/notification handlers are implemented as Lua functions
(see |lsp-handler|).
*lsp-method*
Requests and notifications defined by the LSP specification are referred to as
@ -165,76 +166,132 @@ Requests and notifications defined by the LSP specification are referred to as
They are also listed below. Note that handlers depend on server support: they
won't run if your server doesn't support them.
- callHierarchy/incomingCalls
- callHierarchy/outgoingCalls
- textDocument/codeAction
- textDocument/completion
- textDocument/declaration*
- textDocument/definition
- textDocument/diagnostic
- textDocument/documentHighlight
- textDocument/documentSymbol
- textDocument/formatting
- textDocument/hover
- textDocument/implementation*
- textDocument/inlayHint
- textDocument/prepareTypeHierarchy
- textDocument/publishDiagnostics
- textDocument/rangeFormatting
- textDocument/references
- textDocument/rename
- textDocument/semanticTokens/full
- textDocument/semanticTokens/full/delta
- textDocument/signatureHelp
- textDocument/typeDefinition*
- typeHierarchy/subtypes
- typeHierarchy/supertypes
- window/logMessage
- window/showMessage
- window/showDocument
- window/showMessageRequest
- workspace/applyEdit
- workspace/configuration
- workspace/executeCommand
- workspace/inlayHint/refresh
- workspace/symbol
- workspace/workspaceFolders
handler type ~
------------------------------------------ -------------- ~
$/progress notification
workspace/executeCommand response
window/workDoneProgress/create request
window/showMessageRequest request
client/registerCapability request
client/unregisterCapability request
workspace/applyEdit request
workspace/configuration request
workspace/workspaceFolders request
textDocument/publishDiagnostics notification
textDocument/diagnostic response
textDocument/codeLens response
textDocument/inlayHint response
workspace/inlayHint/refresh request
textDocument/references response
textDocument/documentSymbol response
workspace/symbol response
textDocument/rename response
textDocument/formatting response
textDocument/rangeFormatting response
textDocument/completion response
textDocument/hover response
textDocument/declaration* response
textDocument/definition response
textDocument/implementation* response
textDocument/typeDefinition* response
textDocument/signatureHelp response
textDocument/documentHighlight response
callHierarchy/incomingCalls response
callHierarchy/outgoingCalls response
typeHierarchy/subtypes response
typeHierarchy/supertypes response
window/logMessage notification
window/showMessage notification
window/showDocument request
workspace/semanticTokens/refresh request
Legend (see |lsp-handler|): ~
response : LSP server sends a response to request made by client (Nvim)
request : LSP server sends a request to client (Nvim)
notification : LSP server sends a notification to client (Nvim)
*lsp-handler*
LSP handlers are functions that handle |lsp-response|s to requests made by Nvim
to the server. (Notifications, as opposed to requests, are fire-and-forget:
there is no response, so they can't be handled. |lsp-notification|)
LSP handlers are functions executed on the Nvim's side (LSP client):
(i) that handle |lsp-response|s to requests made by Nvim to LSP server
(Lua type: `vim.lsp.ResponseHandler`), or
(ii) that handle |lsp-request|s or |lsp-notification|s made by LSP server
(Lua type: `vim.lsp.RequestHandler` or `vim.lsp.NotificationHandler`).
Each response handler has this signature: >
Notifications (|lsp-notification|) made by Nvim, as opposed to requests, are
fire-and-forget: there is no response from LSP server, so they can't be
handled.
function(err, result, ctx, config)
Each type of the LSP handlers has the following signature (`vim.lsp.Handler`):
>
vim.lsp.ResponseHandler:
fun(err, result, ctx, config)
vim.lsp.NotificationHandler:
fun(err, params, ctx, config)
vim.lsp.RequestHandler:
fun(err, params, ctx, config): Result?, lsp.ResponseError?
<
Parameters: ~
- {err} (table|nil) Error info dict, or `nil` if the request
completed.
- {result} (Result | Params | nil) `result` key of the |lsp-response| or
`nil` if the request failed.
- {ctx} (table) Table of calling state associated with the
handler, with these keys:
- {method} (string) |lsp-method| name.
- {client_id} (number) |vim.lsp.Client| identifier.
- {bufnr} (Buffer) Buffer handle.
- {params} (table|nil) Request parameters table.
- {version} (number) Document version at time of
• {err} (`lsp.LspResponseError?`) Error info table, or `nil` if
the request completed without errors.
• {result} (`Result`) readout of `result` key in the |lsp-response|,
or `nil` if the request failed (i.e. {err} `~= nil`); or
{request} (`Params`) readout of `params` key in the |lsp-request| or
|lsp-notification|, or `nil` if the method does not
require params.
• {ctx} (`lsp.HandlerContext`) table of calling state associated
with the handler, with these keys:
• {method} (`string`) |lsp-method| name.
• {client_id} (`number`) |vim.lsp.Client| identifier.
• {bufnr} (`number`) Buffer handle.
• {params} (`table?`) Request parameters table.
• {version} (`number`) Document version at time of
request. Handlers can compare this to the
current document version to check if the
response is "stale". See also |b:changedtick|.
- {config} (table) Handler-defined configuration table, which allows
• {config} (`table`) Handler-defined configuration table, which allows
users to customize handler behavior.
For an example, see:
|vim.lsp.diagnostic.on_publish_diagnostics()|
To configure a particular |lsp-handler|, see:
|lsp-handler-configuration|
|lsp-handler-configuration| |vim.lsp.with()|
Returns: ~
Two values `result, err` where `err` is shaped like an RPC error: >
Return (multiple): ~
(`Result?`) `result` on successful request, or `nil` otherwise.
See |lsp-handler-return|
(`lsp.ResponseError?`) `error` on unsuccessful request, or `nil` otherwise.
|lsp-response| and |lsp-notification| handlers do not have return
values, i.e., equivalent to both being `nil`.
*lsp-handler-return*
Return values and error handling of |lsp-handler|:
For |lsp-response| and |lsp-notification| handlers, there are no return values
(i.e. both `result` and `error` are `nil`).
For |lsp-request| handlers, return either non-nil `result` (on success) or
`error` (on failure), but not both.
Request handlers |lsp-request| should return a valid `result` object as
specified in the LSP protocol, which will be sent back to the LSP server
via JSON RPC (as a part of |lsp-response| message), indicating the request
was handled successfully. Any null or void values in the result (the
entire `result` or any null values contained in a list, table, etc.) must
be converted to and represented by |vim.NIL|, rather than `nil`.
If an error happens and the request is not succesful, handler functions
must return `nil` for `result` and an `lsp.ResponseError` object for `error`.
The first return value `nil` (not `vim.NIL`) of a LSP response handler means
that the LSP request was not successful. `error` (`lsp.ResponseError`) is
structured like: >
{ code, message, data? }
< You can use |vim.lsp.rpc.rpc_response_error()| to create this object.
< You can use |vim.lsp.rpc.rpc_response_error()| to create this object.
See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#responseMessage
*lsp-handler-configuration*
@ -344,6 +401,7 @@ in the following order:
Log levels are defined in |vim.log.levels|
------------------------------------------------------------------------------
VIM.LSP.PROTOCOL *vim.lsp.protocol*
Module `vim.lsp.protocol` defines constants dictated by the LSP specification,
@ -356,14 +414,22 @@ name: >lua
vim.lsp.protocol.TextDocumentSyncKind.Full == 1
vim.lsp.protocol.TextDocumentSyncKind[1] == "Full"
<
*lsp-request*
LSP request shape: >
{ id: integer|string, method: string, params?: Params }
< https://microsoft.github.io/language-server-protocol/specifications/specification-current/#requestMessage
*lsp-response*
LSP response shape:
https://microsoft.github.io/language-server-protocol/specifications/specification-current/#responseMessage
LSP response shape: >
{ id: integer|string|nil, result: Result, error: nil } (on success)
{ id: integer|string|nil, result: nil, error: ResponseError } (on error)
< https://microsoft.github.io/language-server-protocol/specifications/specification-current/#responseMessage
*lsp-notification*
LSP notification shape:
https://microsoft.github.io/language-server-protocol/specifications/specification-current/#notificationMessage
LSP notification shape: >
{ method: string, params?: Params }
< https://microsoft.github.io/language-server-protocol/specifications/specification-current/#notificationMessage
================================================================================
LSP HIGHLIGHT *lsp-highlight*
@ -932,7 +998,7 @@ with({handler}, {override_config}) *vim.lsp.with()*
Function to manage overriding defaults for LSP handlers.
Parameters: ~
• {handler} (`lsp.Handler`) See |lsp-handler|
• {handler} (`vim.lsp.Handler`) See |lsp-handler|
• {override_config} (`table`) Table containing the keys to override
behavior of the {handler}
@ -954,7 +1020,7 @@ Lua module: vim.lsp.client *lsp-client*
with the server. You can modify this in the
`config`'s `on_init` method before text is
sent to the server.
• {handlers} (`table<string,lsp.Handler>`) The handlers
• {handlers} (`table<string,vim.lsp.Handler>`) The handlers
used by the client as described in
|lsp-handler|.
• {requests} (`table<integer,{ type: string, bufnr: integer, method: string}>`)
@ -1018,7 +1084,7 @@ Lua module: vim.lsp.client *lsp-client*
• {capabilities} (`lsp.ClientCapabilities`) The capabilities
provided by the client (editor or tool)
• {dynamic_capabilities} (`lsp.DynamicCapabilities`)
• {request} (`fun(method: string, params: table?, handler: lsp.Handler?, bufnr: integer?): boolean, integer?`)
• {request} (`fun(method: string, params: table?, handler: vim.lsp.Handler?, bufnr: integer): boolean, integer?`)
Sends a request to the server. This is a thin
wrapper around {client.rpc.request} with some
additional checking. If {handler} is not
@ -1495,13 +1561,13 @@ on_diagnostic({_}, {result}, {ctx}, {config})
<
Parameters: ~
• {result} (`lsp.DocumentDiagnosticReport`)
• {result} (`lsp.DocumentDiagnosticReport`) TODO verify partial results
• {ctx} (`lsp.HandlerContext`)
• {config} (`vim.diagnostic.Opts`) Configuration table (see
|vim.diagnostic.config()|).
*vim.lsp.diagnostic.on_publish_diagnostics()*
on_publish_diagnostics({_}, {result}, {ctx}, {config})
on_publish_diagnostics({_}, {params}, {ctx}, {config})
|lsp-handler| for the method "textDocument/publishDiagnostics"
See |vim.diagnostic.config()| for configuration options. Handler-specific
@ -1526,7 +1592,7 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config})
<
Parameters: ~
• {result} (`lsp.PublishDiagnosticsParams`)
• {params} (`lsp.PublishDiagnosticsParams`)
• {ctx} (`lsp.HandlerContext`)
• {config} (`vim.diagnostic.Opts?`) Configuration table (see
|vim.diagnostic.config()|).
@ -1566,7 +1632,7 @@ on_codelens({err}, {result}, {ctx}) *vim.lsp.codelens.on_codelens()*
Parameters: ~
• {err} (`lsp.ResponseError?`)
• {result} (`lsp.CodeLens[]`)
• {result} (`lsp.CodeLens[]?`)
• {ctx} (`lsp.HandlerContext`)
refresh({opts}) *vim.lsp.codelens.refresh()*
@ -1763,7 +1829,7 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()*
<
Parameters: ~
• {result} (`lsp.Hover`)
• {result} (`lsp.Hover?`)
• {ctx} (`lsp.HandlerContext`)
• {config} (`table`) Configuration table.
• border: (default=nil)
@ -1785,7 +1851,7 @@ signature_help({_}, {result}, {ctx}, {config})
<
Parameters: ~
• {result} (`lsp.SignatureHelp`) Response from the language server
• {result} (`lsp.SignatureHelp?`) Response from the language server
• {ctx} (`lsp.HandlerContext`) Client context
• {config} (`table`) Configuration table.
• border: (default=nil)
@ -1816,7 +1882,7 @@ apply_text_edits({text_edits}, {bufnr}, {offset_encoding})
Applies a list of text edits to a buffer.
Parameters: ~
• {text_edits} (`table`) list of `TextEdit` objects
• {text_edits} (`lsp.TextEdit[]`) list of `TextEdit` objects
• {bufnr} (`integer`) Buffer id
• {offset_encoding} (`string`) utf-8|utf-16|utf-32
@ -1846,8 +1912,8 @@ buf_highlight_references({bufnr}, {references}, {offset_encoding})
Parameters: ~
• {bufnr} (`integer`) Buffer id
• {references} (`table`) List of `DocumentHighlight` objects to
highlight
• {references} (`lsp.DocumentHighlight[]`) List of
`DocumentHighlight` objects to highlight
• {offset_encoding} (`string`) One of "utf-8", "utf-16", "utf-32".
See also: ~
@ -2187,8 +2253,11 @@ symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()*
Converts symbols to quickfix list items.
Parameters: ~
• {symbols} (`table`) DocumentSymbol[] or SymbolInformation[]
• {bufnr} (`integer`)
• {symbols} (`lsp.DocumentSymbol[]|lsp.WorkspaceSymbol[]|lsp.SymbolInformation[]`)
• {bufnr} (`integer?`)
Return: ~
(`vim.lsp.util.LocationItem[]`)
==============================================================================

View File

@ -233,6 +233,7 @@ The following new APIs and features were added.
when deleting buffers, and avoids "invalid buffer" cases. #25461
• LSP
• Lua type annotations for LSP protocol and |lsp-handler|s.
• LSP method names are available in |vim.lsp.protocol.Methods|.
• Implemented LSP inlay hints: |lsp-inlay_hint|
https://microsoft.github.io/language-server-protocol/specification/#textDocument_inlayHint

View File

@ -837,10 +837,10 @@ api.nvim_create_autocmd('VimLeavePre', {
--- Sends an async request for all active clients attached to the
--- buffer.
---
---@param bufnr (integer) Buffer handle, or 0 for current.
---@param method (string) LSP method name
---@param bufnr integer Buffer handle, or 0 for current.
---@param method string LSP method name, see |vim.lsp.protocol.Methods|
---@param params table|nil Parameters to send to the server
---@param handler? lsp.Handler See |lsp-handler|
---@param handler? vim.lsp.ResponseHandler See |lsp-handler|
--- If nil, follows resolution strategy defined in |lsp-handler-configuration|
---
---@return table<integer, integer> client_request_ids Map of client-id:request-id pairs
@ -892,9 +892,9 @@ end
--- Sends an async request for all active clients attached to the buffer and executes the `handler`
--- callback with the combined result.
---
---@param bufnr (integer) Buffer handle, or 0 for current.
---@param method (string) LSP method name
---@param params (table|nil) Parameters to send to the server
---@param bufnr integer Buffer handle, or 0 for current.
---@param method string LSP method name
---@param params table|nil Parameters to send to the server
---@param handler fun(results: table<integer, {error: lsp.ResponseError, result: any}>) (function)
--- Handler called after all requests are completed. Server results are passed as
--- a `client_id:result` map.
@ -1151,7 +1151,7 @@ function lsp.for_each_buffer_client(bufnr, fn)
end
--- Function to manage overriding defaults for LSP handlers.
---@param handler (lsp.Handler) See |lsp-handler|
---@param handler vim.lsp.Handler See |lsp-handler|
---@param override_config (table) Table containing the keys to override behavior of the {handler}
function lsp.with(handler, override_config)
return function(err, result, ctx, config)

View File

@ -1,7 +1,21 @@
---@meta
error('Cannot require a meta file')
---@alias lsp.Handler fun(err: lsp.ResponseError?, result: any, context: lsp.HandlerContext, config?: table): ...any
-- TODO: Consider moving this to vim/lsp/handlers.lua; or stay here?
---LSP Handlers on the Nvim side, see |lsp-handler| for documentation.
---See also |lsp-handler-resolution|
---@alias vim.lsp.Handler vim.lsp.ResponseHandler | vim.lsp.RequestHandler | vim.lsp.NotificationHandler
---
---Handles a response from the server, see |lsp-response|
---@alias vim.lsp.ResponseHandler fun(err: lsp.ResponseError?, result: any, context: lsp.HandlerContext, config?: table)
---
---Handles a request made from the server, see |lsp-request| and |lsp-handler|.
---Returns either an `result` object or a `ResponseError` object to send back to LSP. see |lsp-handler-return|
---@alias vim.lsp.RequestHandler fun(err: lsp.ResponseError?, params: any, context: lsp.HandlerContext, config?: table): lsp.LSPAny?, lsp.ResponseError?
---
---Handles a notification sent from the server, see |lsp-notification|
---@alias vim.lsp.NotificationHandler fun(err: lsp.ResponseError?, params: any, context: lsp.HandlerContext, config?: table)
---@class lsp.HandlerContext
---@field method string
@ -10,7 +24,8 @@ error('Cannot require a meta file')
---@field params? any
---@field version? integer
-- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#responseMessage
---@class lsp.ResponseError
---@field code integer
---@field code integer see `lsp.ErrorCodes` and `lsp.LSPErrorCodes`.
---@field message string
---@field data string|number|boolean|table[]|table|nil

View File

@ -11,8 +11,7 @@ local M = {}
---
---@param method (string) LSP method name
---@param params (table|nil) Parameters to send to the server
---@param handler lsp.Handler? See |lsp-handler|. Follows |lsp-handler-resolution|
---
---@param handler vim.lsp.Handler? See |lsp-handler|. Follows |lsp-handler-resolution|
---@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
@ -826,7 +825,7 @@ end
--- cursor position.
---
---@param options? vim.lsp.buf.code_action.Opts
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction
---@see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction
---@see vim.lsp.protocol.CodeActionTriggerKind
function M.code_action(options)
validate({ options = { options, 't', true } })
@ -860,9 +859,11 @@ function M.code_action(options)
---@type table<integer, vim.lsp.CodeActionResultEntry>
local results = {}
--- Handler for textDocument/codeAction
---@param err? lsp.ResponseError
---@param result? (lsp.Command|lsp.CodeAction)[]
---@param ctx lsp.HandlerContext
---@type vim.lsp.ResponseHandler
local function on_result(err, result, ctx)
results[ctx.client_id] = { error = err, result = result, ctx = ctx }
remaining = remaining - 1

View File

@ -153,7 +153,7 @@ local validate = vim.validate
--- @field offset_encoding string
---
--- The handlers used by the client as described in |lsp-handler|.
--- @field handlers table<string,lsp.Handler>
--- @field handlers table<string,vim.lsp.Handler>
---
--- The current pending requests in flight to the server. Entries are key-value
--- pairs with the key being the request id while the value is a table with
@ -229,7 +229,7 @@ local validate = vim.validate
--- If {status} is `true`, the function returns {request_id} as the second
--- result. You can use this with `client.cancel_request(request_id)` to cancel
--- the request.
--- @field request fun(method: string, params: table?, handler: lsp.Handler?, bufnr: integer?): boolean, integer?
--- @field request fun(method: string, params: table?, handler: vim.lsp.Handler?, bufnr: integer): boolean, integer?
---
--- Sends a request to the server and synchronously waits for the response.
--- This is a wrapper around {client.request}
@ -628,7 +628,7 @@ end
--- Returns the default handler if the user hasn't set a custom one.
---
--- @param method (string) LSP method name
--- @return lsp.Handler|nil handler for the given method, if defined, or the default from |vim.lsp.handlers|
--- @return vim.lsp.Handler|nil handler for the given method, if defined, or the default from |vim.lsp.handlers|
function Client:_resolve_handler(method)
return self.handlers[method] or lsp.handlers[method]
end
@ -653,7 +653,7 @@ end
---
--- @param method string LSP method name.
--- @param params? table LSP request params.
--- @param handler? lsp.Handler Response |lsp-handler| for this method.
--- @param handler? vim.lsp.Handler Response |lsp-handler| for this method.
--- @param bufnr? integer Buffer handle (0 for current).
--- @return boolean status, integer? request_id {status} is a bool indicating
--- whether the request was successful. If it is `false`, then it will
@ -865,7 +865,7 @@ end
---
--- @param command lsp.Command
--- @param context? {bufnr: integer}
--- @param handler? lsp.Handler only called if a server command
--- @param handler? vim.lsp.Handler only called if a server command
function Client:_exec_cmd(command, context, handler)
context = vim.deepcopy(context or {}, true) --[[@as lsp.HandlerContext]]
context.bufnr = context.bufnr or api.nvim_get_current_buf()
@ -999,7 +999,7 @@ end
--- @param params table The parameters for that method.
function Client:_notification(method, params)
log.trace('notification', method, params)
local handler = self:_resolve_handler(method)
local handler = self:_resolve_handler(method) --[[@as vim.lsp.NotificationHandler]]
if handler then
-- Method name is provided here for convenience.
handler(nil, params, { method = method, client_id = self.id })
@ -1012,10 +1012,10 @@ end
--- @param method (string) LSP method name
--- @param params (table) The parameters for that method
--- @return any result
--- @return lsp.ResponseError error code and message set in case an exception happens during the request.
--- @return lsp.ResponseError? error code and message set in case an exception happens during the request.
function Client:_server_request(method, params)
log.trace('server_request', method, params)
local handler = self:_resolve_handler(method)
local handler = self:_resolve_handler(method) --[[@as vim.lsp.RequestHandler]]
if handler then
log.trace('server_request: found handler for', method)
return handler(nil, params, { method = method, client_id = self.id })

View File

@ -258,9 +258,10 @@ end
--- |lsp-handler| for the method `textDocument/codeLens`
---
---@param err lsp.ResponseError?
---@param result lsp.CodeLens[]
---@param ctx lsp.HandlerContext
--- @param err lsp.ResponseError?
--- @param result lsp.CodeLens[]?
--- @param ctx lsp.HandlerContext
--- @type vim.lsp.ResponseHandler
function M.on_codelens(err, result, ctx, _)
if err then
active_refreshes[assert(ctx.bufnr)] = nil

View File

@ -228,7 +228,7 @@ end
--- @param uri string
--- @param client_id? integer
--- @param diagnostics vim.Diagnostic[]
--- @param diagnostics vim.Diagnostic[]|lsp.Diagnostic[] TODO: review type
--- @param is_pull boolean
--- @param config? vim.diagnostic.Opts
local function handle_diagnostics(uri, client_id, diagnostics, is_pull, config)
@ -286,11 +286,12 @@ end
--- ```
---
---@param _ lsp.ResponseError?
---@param result lsp.PublishDiagnosticsParams
---@param params lsp.PublishDiagnosticsParams
---@param ctx lsp.HandlerContext
---@param config? vim.diagnostic.Opts Configuration table (see |vim.diagnostic.config()|).
function M.on_publish_diagnostics(_, result, ctx, config)
handle_diagnostics(result.uri, ctx.client_id, result.diagnostics, false, config)
---@type vim.lsp.NotificationHandler
function M.on_publish_diagnostics(_, params, ctx, config)
handle_diagnostics(params.uri, ctx.client_id, params.diagnostics, false, config)
end
--- |lsp-handler| for the method "textDocument/diagnostic"
@ -319,9 +320,10 @@ end
--- ```
---
---@param _ lsp.ResponseError?
---@param result lsp.DocumentDiagnosticReport
---@param result lsp.DocumentDiagnosticReport TODO verify partial results
---@param ctx lsp.HandlerContext
---@param config vim.diagnostic.Opts Configuration table (see |vim.diagnostic.config()|).
---@type vim.lsp.ResponseHandler
function M.on_diagnostic(_, result, ctx, config)
if result == nil or result.kind == 'unchanged' then
return

View File

@ -4,7 +4,7 @@ local ms = protocol.Methods
local util = require('vim.lsp.util')
local api = vim.api
--- @type table<string,lsp.Handler>
--- @type table<string, vim.lsp.Handler>
local M = {}
-- FIXME: DOC: Expose in vimdocs
@ -16,68 +16,77 @@ local function err_message(...)
api.nvim_command('redraw')
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
--- @type vim.lsp.ResponseHandler
M[ms.workspace_executeCommand] = function(_, _, _, _)
-- Error handling is done implicitly by wrapping all handlers; see end of this file
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress
---@param result lsp.ProgressParams
---@param ctx lsp.HandlerContext
M[ms.dollar_progress] = function(_, result, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress
--- @param params lsp.ProgressParams
--- @param ctx lsp.HandlerContext
--- @type vim.lsp.NotificationHandler
M[ms.dollar_progress] = function(_, params, ctx)
local client = vim.lsp.get_client_by_id(ctx.client_id)
if not client then
err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update')
-- TODO(wookayin): This is a notification handler, so should be removed (after testing!) #16472
return vim.NIL
end
local kind = nil
local value = result.value
local value = params.value
if type(value) == 'table' then
---@cast value lsp.WorkDoneProgressBegin|lsp.WorkDoneProgressReport|lsp.WorkDoneProgressEnd
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
client.progress.pending[params.token] = value.title
else
value.title = client.progress.pending[result.token]
value.title = client.progress.pending[params.token]
if kind == 'end' then
client.progress.pending[result.token] = nil
client.progress.pending[params.token] = nil
end
end
end
client.progress:push(result)
client.progress:push(params)
api.nvim_exec_autocmds('LspProgress', {
pattern = kind,
modeline = false,
data = { client_id = ctx.client_id, result = result },
-- TODO(wookayin): breaking change during 0.10-nightly, results -> params. Revise data again
data = { client_id = ctx.client_id, result = params },
})
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create
---@param result lsp.WorkDoneProgressCreateParams
---@param ctx lsp.HandlerContext
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create
--- @param result lsp.WorkDoneProgressCreateParams
--- @return vim.NIL void On a successful request, return void.
--- @type vim.lsp.RequestHandler
M[ms.window_workDoneProgress_create] = function(_, result, ctx)
local client = vim.lsp.get_client_by_id(ctx.client_id)
if not client then
err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update')
-- TODO(wookayin): This is an error case, so should not send the success signal; related #16472
return vim.NIL
end
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[ms.window_showMessageRequest] = function(_, result)
local actions = result.actions or {}
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessageRequest
--- @param params lsp.ShowMessageRequestParams
--- @return lsp.MessageActionItem|vim.NIL result: the selected MessageActionItem, or null if none got selected.
--- @type vim.lsp.RequestHandler
M[ms.window_showMessageRequest] = function(_, params, _, _)
local actions = params.actions or {}
local co, is_main = coroutine.running()
if co and not is_main then
local opts = {
prompt = result.message .. ': ',
prompt = params.message .. ': ',
format_item = function(action)
return (action.title:gsub('\r\n', '\\r\\n')):gsub('\n', '\\n')
end,
@ -91,7 +100,7 @@ M[ms.window_showMessageRequest] = function(_, result)
end)
return coroutine.yield()
else
local option_strings = { result.message, '\nRequest Actions:' }
local option_strings = { params.message, '\nRequest Actions:' }
for i, action in ipairs(actions) do
local title = action.title:gsub('\r\n', '\\r\\n')
title = title:gsub('\n', '\\n')
@ -106,20 +115,22 @@ M[ms.window_showMessageRequest] = function(_, result)
end
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability
--- @param result lsp.RegistrationParams
M[ms.client_registerCapability] = function(_, result, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability
--- @param params lsp.RegistrationParams
--- @return vim.NIL void On a successful request, return void.
--- @type vim.lsp.RequestHandler
M[ms.client_registerCapability] = function(_, params, ctx, _)
local client_id = ctx.client_id
local client = assert(vim.lsp.get_client_by_id(client_id))
client.dynamic_capabilities:register(result.registrations)
client.dynamic_capabilities:register(params.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
for _, reg in ipairs(params.registrations) do
if reg.method == ms.workspace_didChangeWatchedFiles then
vim.lsp._watchfiles.register(reg, ctx)
elseif not client.dynamic_capabilities:supports_registration(reg.method) then
@ -137,14 +148,16 @@ M[ms.client_registerCapability] = function(_, result, ctx)
return vim.NIL
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability
--- @param result lsp.UnregistrationParams
M[ms.client_unregisterCapability] = function(_, result, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability
--- @param params lsp.UnregistrationParams
--- @return vim.NIL void On a successful request, return void.
--- @type vim.lsp.RequestHandler
M[ms.client_unregisterCapability] = function(_, params, ctx, _)
local client_id = ctx.client_id
local client = assert(vim.lsp.get_client_by_id(client_id))
client.dynamic_capabilities:unregister(result.unregisterations)
client.dynamic_capabilities:unregister(params.unregisterations)
for _, unreg in ipairs(result.unregisterations) do
for _, unreg in ipairs(params.unregisterations) do
if unreg.method == ms.workspace_didChangeWatchedFiles then
vim.lsp._watchfiles.unregister(unreg, ctx)
end
@ -152,8 +165,11 @@ M[ms.client_unregisterCapability] = function(_, result, ctx)
return vim.NIL
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
M[ms.workspace_applyEdit] = function(_, workspace_edit, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
--- @param workspace_edit lsp.ApplyWorkspaceEditParams
--- @return lsp.ApplyWorkspaceEditResult result
--- @type vim.lsp.RequestHandler
M[ms.workspace_applyEdit] = function(_, workspace_edit, ctx, _)
assert(
workspace_edit,
'workspace/applyEdit must be called with `ApplyWorkspaceEditParams`. Server is violating the specification'
@ -164,12 +180,15 @@ M[ms.workspace_applyEdit] = function(_, workspace_edit, ctx)
if workspace_edit.label then
print('Workspace edit', workspace_edit.label)
end
local status, result =
local status, errmsg =
pcall(util.apply_workspace_edit, workspace_edit.edit, client.offset_encoding)
return {
---@type lsp.ApplyWorkspaceEditResult
local result = {
applied = status,
failureReason = result,
failureReason = errmsg,
}
return result
end
---@param table table e.g., { foo = { bar = "z" } }
@ -180,9 +199,11 @@ local function lookup_section(table, section)
return vim.tbl_get(table, unpack(keys))
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_configuration
--- @param result lsp.ConfigurationParams
M[ms.workspace_configuration] = function(_, result, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_configuration
--- @param params lsp.ConfigurationParams
--- @return lsp.LSPAny[] result
--- @type vim.lsp.RequestHandler
M[ms.workspace_configuration] = function(_, params, ctx, _)
local client_id = ctx.client_id
local client = vim.lsp.get_client_by_id(client_id)
if not client then
@ -193,12 +214,13 @@ M[ms.workspace_configuration] = function(_, result, ctx)
)
return
end
if not result.items then
if not params.items then
return {}
end
---@type lsp.LSPAny[]
local response = {}
for _, item in ipairs(result.items) do
for _, item in ipairs(params.items) do
if item.section then
local value = lookup_section(client.settings, item.section)
-- For empty sections with no explicit '' key, return settings as is
@ -214,8 +236,13 @@ M[ms.workspace_configuration] = function(_, result, ctx)
return response
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders
M[ms.workspace_workspaceFolders] = function(_, _, ctx)
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders
--- Fetchs the current open list of workspace folders on the client.
--- Returns null if only a single file is open in the tool;
--- Returns an empty array if a workspace is open but no folders are configured.
--- @return lsp.WorkspaceFolder[]|vim.NIL result: list workspace folders, or vim.NIL if single-file.
--- @type vim.lsp.RequestHandler
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
@ -225,23 +252,39 @@ M[ms.workspace_workspaceFolders] = function(_, _, ctx)
return client.workspace_folders or vim.NIL
end
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_publishDiagnostics
--- @type vim.lsp.NotificationHandler
M[ms.textDocument_publishDiagnostics] = function(...)
return vim.lsp.diagnostic.on_publish_diagnostics(...)
end
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_diagnostic
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_diagnostic] = function(...)
return vim.lsp.diagnostic.on_diagnostic(...)
end
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeLens
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_codeLens] = function(...)
return vim.lsp.codelens.on_codelens(...)
end
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_inlayHint
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_inlayHint] = function(...)
return vim.lsp.inlay_hint.on_inlayhint(...)
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
--- @see: https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh
--- @type vim.lsp.RequestHandler
M[ms.workspace_inlayHint_refresh] = function(...)
return vim.lsp.inlay_hint.on_refresh(...)
end
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
--- @param result lsp.Location[]|nil
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_references] = function(_, result, ctx, config)
if not result or vim.tbl_isempty(result) then
vim.notify('No references found')
@ -272,11 +315,13 @@ end
---
--- loclist: (boolean) use the location list (default is to use the quickfix list)
---
---@param map_result function `((resp, bufnr) -> list)` to convert the response
---@param map_result fun(resp: lsp.DocumentSymbol[]|lsp.WorkspaceSymbol[]|lsp.SymbolInformation[], bufnr: integer|nil):vim.lsp.util.LocationItem[]
--- Function `((resp, bufnr) -> list)` to convert the LSP response into location items
---@param entity string name of the resource used in a `not found` error message
---@param title_fn fun(ctx: lsp.HandlerContext): string Function to call to generate list title
---@return lsp.Handler
local function response_to_list(map_result, entity, title_fn)
---@return vim.lsp.ResponseHandler
local function _response_to_list_handler(map_result, entity, title_fn)
---@type vim.lsp.ResponseHandler
return function(_, result, ctx, config)
if not result or vim.tbl_isempty(result) then
vim.notify('No ' .. entity .. ' found')
@ -299,8 +344,9 @@ local function response_to_list(map_result, entity, title_fn)
end
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
M[ms.textDocument_documentSymbol] = response_to_list(
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_documentSymbol] = _response_to_list_handler(
util.symbols_to_items,
'document symbols',
function(ctx)
@ -309,12 +355,18 @@ M[ms.textDocument_documentSymbol] = response_to_list(
end
)
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol
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/#workspace_symbol
M[ms.workspace_symbol] = _response_to_list_handler(
util.symbols_to_items,
'workspace 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
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename
--- @param result lsp.WorkspaceEdit?
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_rename] = function(_, result, ctx, _)
if not result then
vim.notify("Language server couldn't provide rename result", vim.log.levels.INFO)
@ -324,7 +376,9 @@ M[ms.textDocument_rename] = function(_, result, ctx, _)
util.apply_workspace_edit(result, client.offset_encoding)
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting
--- @param result lsp.TextEdit[]?
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_rangeFormatting] = function(_, result, ctx, _)
if not result then
return
@ -333,7 +387,9 @@ M[ms.textDocument_rangeFormatting] = function(_, result, ctx, _)
util.apply_text_edits(result, ctx.bufnr, client.offset_encoding)
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
--- @param result lsp.TextEdit[]?
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_formatting] = function(_, result, ctx, _)
if not result then
return
@ -342,9 +398,11 @@ M[ms.textDocument_formatting] = function(_, result, ctx, _)
util.apply_text_edits(result, ctx.bufnr, client.offset_encoding)
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
--- @param result lsp.CompletionItem[] | lsp.CompletionList | nil
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_completion] = function(_, result, _, _)
if vim.tbl_isempty(result or {}) then
if result == nil or vim.tbl_isempty(result) then
return
end
local cursor = api.nvim_win_get_cursor(0)
@ -371,13 +429,14 @@ end
--- )
--- ```
---
---@param _ lsp.ResponseError?
---@param result lsp.Hover
---@param ctx lsp.HandlerContext
---@param config table Configuration table.
--- @param _ lsp.ResponseError?
--- @param result lsp.Hover|nil
--- @param ctx lsp.HandlerContext
--- @param config table Configuration table.
--- - border: (default=nil)
--- - Add borders to the floating window
--- - See |vim.lsp.util.open_floating_preview()| for more options.
--- @type vim.lsp.ResponseHandler
function M.hover(_, result, ctx, config)
config = config or {}
config.focus_id = ctx.method
@ -408,19 +467,20 @@ function M.hover(_, result, ctx, config)
return util.open_floating_preview(contents, format, config)
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_hover] = M.hover
--- Jumps to a location. Used as a handler for multiple LSP methods.
---@param _ nil not used
---@param result (table) result of LSP method; a location or a list of locations.
---@param ctx (lsp.HandlerContext) table containing the context of the request, including the method
---@param config? vim.lsp.LocationOpts
---(`textDocument/definition` can return `Location` or `Location[]`
--- @param _ any not used (error code)
--- @param result lsp.Location|lsp.Location[]|lsp.LocationLink[]|nil
--- @param ctx lsp.HandlerContext table containing the context of the request, including the method
--- @param config? vim.lsp.LocationOpts
--- @type vim.lsp.ResponseHandler
local function location_handler(_, result, ctx, config)
if result == nil or vim.tbl_isempty(result) then
log.info(ctx.method, 'No location found')
return nil
return
end
local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
@ -448,13 +508,20 @@ local function location_handler(_, result, ctx, config)
api.nvim_command('botright copen')
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_declaration] = location_handler
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_definition] = location_handler
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_typeDefinition] = location_handler
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_implementation] = location_handler
--- |lsp-handler| for the method "textDocument/signatureHelp".
@ -471,12 +538,13 @@ M[ms.textDocument_implementation] = location_handler
--- ```
---
---@param _ lsp.ResponseError?
---@param result lsp.SignatureHelp Response from the language server
---@param result lsp.SignatureHelp? Response from the language server
---@param ctx lsp.HandlerContext Client context
---@param config table Configuration table.
--- - border: (default=nil)
--- - Add borders to the floating window
--- - See |vim.lsp.util.open_floating_preview()| for more options
---@type vim.lsp.ResponseHandler
function M.signature_help(_, result, ctx, config)
config = config or {}
config.focus_id = ctx.method
@ -512,10 +580,13 @@ function M.signature_help(_, result, ctx, config)
return fbuf, fwin
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_signatureHelp] = M.signature_help
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight
--- @param result lsp.DocumentHighlight[]?
--- @type vim.lsp.ResponseHandler
M[ms.textDocument_documentHighlight] = function(_, result, ctx, _)
if not result then
return
@ -533,17 +604,21 @@ end
--- Displays call hierarchy in the quickfix window.
---
--- @param direction 'from'|'to' `"from"` for incoming calls and `"to"` for outgoing calls
--- whose {result} param is:
--- `CallHierarchyIncomingCall[]` if {direction} is `"from"`,
--- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`,
--- @overload fun(direction:'from'): fun(_, result: lsp.CallHierarchyIncomingCall[]?)
--- @overload fun(direction:'to'): fun(_, result: lsp.CallHierarchyOutgoingCall[]?)
--- @return vim.lsp.ResponseHandler
local function make_call_hierarchy_handler(direction)
--- @param result lsp.CallHierarchyIncomingCall[]|lsp.CallHierarchyOutgoingCall[]
return function(_, result)
---@param result lsp.CallHierarchyIncomingCall[] | lsp.CallHierarchyOutgoingCall[]
return function(_, result, _, _)
if not result then
return
end
local items = {}
for _, call_hierarchy_call in pairs(result) do
--- @type lsp.CallHierarchyItem
for _, call_hierarchy_call in ipairs(result) do
---@type lsp.CallHierarchyItem
local call_hierarchy_item = call_hierarchy_call[direction]
for _, range in pairs(call_hierarchy_call.fromRanges) do
table.insert(items, {
@ -559,15 +634,18 @@ local function make_call_hierarchy_handler(direction)
end
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls
--- @type vim.lsp.ResponseHandler
M[ms.callHierarchy_incomingCalls] = make_call_hierarchy_handler('from')
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls
--- @type vim.lsp.ResponseHandler
M[ms.callHierarchy_outgoingCalls] = make_call_hierarchy_handler('to')
--- Displays type hierarchy in the quickfix window.
local function make_type_hierarchy_handler()
--- @param result lsp.TypeHierarchyItem[]
--- @type vim.lsp.ResponseHandler
return function(_, result, ctx, _)
if not result then
return
@ -598,17 +676,20 @@ local function make_type_hierarchy_handler()
end
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_incomingCalls
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_subtypes
--- @type vim.lsp.ResponseHandler
M[ms.typeHierarchy_subtypes] = make_type_hierarchy_handler()
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_outgoingCalls
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_supertypes
--- @type vim.lsp.ResponseHandler
M[ms.typeHierarchy_supertypes] = make_type_hierarchy_handler()
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_logMessage
--- @param result lsp.LogMessageParams
M[ms.window_logMessage] = function(_, result, ctx, _)
local message_type = result.type
local message = result.message
--- @param params lsp.LogMessageParams
--- @type vim.lsp.NotificationHandler
M[ms.window_logMessage] = function(_, params, ctx, _)
local message_type = params.type
local message = params.message
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)
@ -624,14 +705,16 @@ M[ms.window_logMessage] = function(_, result, ctx, _)
else
log.debug(message)
end
return result
-- TODO(wookayin): remove return value, should not be used in notification handlers
return params
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessage
--- @param result lsp.ShowMessageParams
M[ms.window_showMessage] = function(_, result, ctx, _)
local message_type = result.type
local message = result.message
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessage
--- @param params lsp.ShowMessageParams
--- @type vim.lsp.NotificationHandler
M[ms.window_showMessage] = function(_, params, ctx, _)
local message_type = params.type
local message = params.message
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)
@ -641,18 +724,21 @@ M[ms.window_showMessage] = function(_, result, ctx, _)
if message_type == protocol.MessageType.Error then
err_message('LSP[', client_name, '] ', message)
else
local message_type_name = protocol.MessageType[message_type]
local message_type_name = protocol.MessageType[message_type] ---@type lsp.MessageType
api.nvim_out_write(string.format('LSP[%s][%s] %s\n', client_name, message_type_name, message))
end
return result
-- TODO(wookayin): remove return value, should not be used; check if this is used anywhere
return params
end
--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument
--- @param result lsp.ShowDocumentParams
M[ms.window_showDocument] = function(_, result, ctx, _)
local uri = result.uri
--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument
--- @param params lsp.ShowDocumentParams
--- @return lsp.ShowDocumentResult
--- @type vim.lsp.RequestHandler
M[ms.window_showDocument] = function(_, params, ctx, _)
local uri = params.uri
if result.external then
if params.external then
-- TODO(lvimuser): ask the user for confirmation
local cmd, err = vim.ui.open(uri)
local ret = cmd and cmd:wait(2000) or nil
@ -680,28 +766,29 @@ M[ms.window_showDocument] = function(_, result, ctx, _)
local location = {
uri = uri,
range = result.selection,
range = params.selection,
}
local success = util.show_document(location, client.offset_encoding, {
reuse_win = true,
focus = result.takeFocus,
focus = params.takeFocus,
})
return { success = success or false }
end
---@see https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh
--- @see: https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh
M[ms.workspace_inlayHint_refresh] = function(err, result, ctx, config)
return vim.lsp.inlay_hint.on_refresh(err, result, ctx, config)
end
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#semanticTokens_refreshRequest
--- @see: https://microsoft.github.io/language-server-protocol/specifications/#semanticTokens_refreshRequest
M[ms.workspace_semanticTokens_refresh] = function(err, result, ctx, _config)
return vim.lsp.semantic_tokens._refresh(err, result, ctx)
end
-- Add boilerplate error validation and logging for all of these.
for k, fn in pairs(M) do
---@param err lsp.ResponseError
M[k] = function(err, result, ctx, config)
if log.trace() then
log.trace('default_handler', ctx.method, {

View File

@ -37,6 +37,7 @@ local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {})
---@param result lsp.InlayHint[]?
---@param ctx lsp.HandlerContext
---@private
---@type vim.lsp.ResponseHandler
function M.on_inlayhint(err, result, ctx, _)
if err then
log.error('inlayhint', err)
@ -98,11 +99,15 @@ function M.on_inlayhint(err, result, ctx, _)
api.nvim__redraw({ buf = bufnr, valid = true })
end
--- @private
--- |lsp-handler| for the method `textDocument/inlayHint/refresh`
---@param ctx lsp.HandlerContext
---@private
--- @see: https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh
--- @param ctx lsp.HandlerContext
--- @return vim.NIL void On a successful request, return void.
--- @type vim.lsp.RequestHandler
function M.on_refresh(err, _, ctx, _)
if err then
-- TODO(wookayin): error case; should not return NIL but return an error.
return vim.NIL
end
for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do
@ -113,7 +118,7 @@ function M.on_refresh(err, _, ctx, _)
end
end
return vim.NIL
return vim.NIL -- successful
end
--- Optional filters |kwargs|:

View File

@ -44,6 +44,8 @@ local constants = {
Info = 3,
-- A log message.
Log = 4,
-- A debug message.
Debug = 5,
},
-- The file event type.

View File

@ -305,7 +305,10 @@ function STHighlighter:send_request()
method = method .. '/delta'
params.previousResultId = current_result.result_id
end
local success, request_id = client.request(method, params, function(err, response, ctx)
--- response handlers for "textDocument/semanticTokens/full" and ".../delta".
---@type vim.lsp.ResponseHandler
local handler = function(err, response, ctx, _)
-- look client up again using ctx.client_id instead of using a captured
-- client object
local c = vim.lsp.get_client_by_id(ctx.client_id)
@ -314,7 +317,8 @@ function STHighlighter:send_request()
if not err and c and highlighter then
coroutine.wrap(STHighlighter.process_response)(highlighter, response, c, version)
end
end, self.bufnr)
end
local success, request_id = client.request(method, params, handler, self.bufnr)
if success then
active_request.request_id = request_id
@ -335,7 +339,7 @@ end
--- Finally, a redraw command is issued to force nvim to redraw the screen to
--- pick up changed highlight tokens.
---
---@param response lsp.SemanticTokens|lsp.SemanticTokensDelta
---@param response lsp.SemanticTokens|lsp.SemanticTokensDelta|nil
---@private
function STHighlighter:process_response(response, client, version)
local state = self.client_state[client.id]
@ -776,8 +780,11 @@ end
--- invalidate the current results of all buffers and automatically kick off a
--- new request for buffers that are displayed in a window. For those that aren't, a
--- the BufWinEnter event should take care of it next time it's displayed.
--- @return vim.NIL void On a successful request, return void.
--- @type vim.lsp.RequestHandler
function M._refresh(err, _, ctx)
if err then
-- TODO(wookayin): error, should not return vim.NIL
return vim.NIL
end
@ -792,6 +799,7 @@ function M._refresh(err, _, ctx)
end
end
-- successful
return vim.NIL
end

View File

@ -406,7 +406,7 @@ function M.get_progress_messages()
end
--- Applies a list of text edits to a buffer.
---@param text_edits table list of `TextEdit` objects
---@param text_edits lsp.TextEdit[] list of `TextEdit` objects
---@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
@ -429,6 +429,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
-- Fix reversed range and indexing each text_edits
local index = 0
---@param text_edit lsp.TextEdit
text_edits = vim.tbl_map(function(text_edit)
index = index + 1
text_edit._index = index
@ -443,7 +444,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
text_edit.range['end'] = start
end
return text_edit
end, text_edits)
end, text_edits) --[[ @as lsp.TextEdit[] ]]
-- Sort text_edits
table.sort(text_edits, function(a, b)
@ -636,10 +637,10 @@ end
--- |complete-items|.
---
---@deprecated
---@param result table The result of a `textDocument/completion` call, e.g.
--- from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`,
--- `CompletionList` or `null`
---@param prefix (string) the prefix to filter the completion items
---@param result lsp.CompletionItem[]|lsp.CompletionList The result of a `textDocument/completion`
--- call, e.g. from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`,
--- `CompletionList`.
---@param prefix string the prefix to filter the completion items
---@return table[] items
---@see complete-items
function M.text_document_completion_list_to_complete_items(result, prefix)
@ -1797,7 +1798,7 @@ do --[[ References ]]
--- Shows a list of document highlights for a certain buffer.
---
---@param bufnr integer Buffer id
---@param references table List of `DocumentHighlight` objects to highlight
---@param references lsp.DocumentHighlight[] 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/specification/#textDocumentContentChangeEvent
function M.buf_highlight_references(bufnr, references, offset_encoding)
@ -1933,9 +1934,12 @@ end
--- Converts symbols to quickfix list items.
---
---@param symbols table DocumentSymbol[] or SymbolInformation[]
---@param bufnr integer
---@param symbols lsp.DocumentSymbol[] | lsp.WorkspaceSymbol[] | lsp.SymbolInformation[]
---@param bufnr integer?
---@return vim.lsp.util.LocationItem[]
function M.symbols_to_items(symbols, bufnr)
---@param _symbols lsp.DocumentSymbol[] | lsp.WorkspaceSymbol[] | lsp.SymbolInformation[]
---@param _items vim.lsp.util.LocationItem[]
local function _symbols_to_items(_symbols, _items, _bufnr)
for _, symbol in ipairs(_symbols) do
if symbol.location then -- SymbolInformation type
@ -1960,6 +1964,7 @@ function M.symbols_to_items(symbols, bufnr)
})
if symbol.children then
for _, v in ipairs(_symbols_to_items(symbol.children, _items, _bufnr)) do
-- TODO(wookayin): This line will be never executed, seems wrong; validate the correctness
for _, s in ipairs(v) do
table.insert(_items, s)
end

View File

@ -1,12 +1,14 @@
local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local clear = t.clear
local eq = t.eq
local exec_lua = n.exec_lua
local pcall_err = t.pcall_err
local matches = t.matches
describe('lsp-handlers', function()
before_each(clear)
describe('vim.lsp._with_extend', function()
it('should return a table with the default keys', function()
eq(