diff options
author | Gregory Anders <greg@gpanders.com> | 2021-08-22 14:55:28 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-22 13:55:28 -0700 |
commit | c2a211b8e3e00dfae594ccbd9a107aef85a9919c (patch) | |
tree | 727257465343243052b04f4405bdaceda2f05be3 /runtime/lua/vim/lsp | |
parent | 649dbb3b15949aee9d9e25cd39cca1e3e3a4ee45 (diff) | |
download | rneovim-c2a211b8e3e00dfae594ccbd9a107aef85a9919c.tar.gz rneovim-c2a211b8e3e00dfae594ccbd9a107aef85a9919c.tar.bz2 rneovim-c2a211b8e3e00dfae594ccbd9a107aef85a9919c.zip |
docs: make Lua docstrings consistent #15255
The official developer documentation in in :h dev-lua-doc specifies to
use "--@" for special/magic tokens. However, this format is not
consistent with EmmyLua notation (used by some Lua language servers) nor
with the C version of the magic docstring tokens which use three comment
characters.
Further, the code base is currently split between usage of "--@",
"---@", and "--- @". In an effort to remain consistent, change all Lua
magic tokens to use "---@" and update the developer documentation
accordingly.
Diffstat (limited to 'runtime/lua/vim/lsp')
-rw-r--r-- | runtime/lua/vim/lsp/buf.lua | 86 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/codelens.lua | 8 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/diagnostic.lua | 70 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/handlers.lua | 28 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/log.lua | 10 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/protocol.lua | 4 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/rpc.lua | 132 | ||||
-rw-r--r-- | runtime/lua/vim/lsp/util.lua | 314 |
8 files changed, 326 insertions, 326 deletions
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 29f8d6c3bc..250af0a0a7 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -5,7 +5,7 @@ local util = require 'vim.lsp.util' local M = {} ---@private +---@private --- Returns nil if {status} is false or nil, otherwise returns the rest of the --- arguments. local function ok_or_nil(status, ...) @@ -13,31 +13,31 @@ local function ok_or_nil(status, ...) return ... end ---@private +---@private --- Swallows errors. --- ---@param fn Function to run ---@param ... Function arguments ---@returns Result of `fn(...)` if there are no errors, otherwise nil. +---@param fn Function to run +---@param ... Function arguments +---@returns Result of `fn(...)` if there are no errors, otherwise nil. --- Returns nil if errors occur during {fn}, otherwise returns local function npcall(fn, ...) return ok_or_nil(pcall(fn, ...)) end ---@private +---@private --- Sends an async request to all active clients attached to the current --- buffer. --- ---@param method (string) LSP method name ---@param params (optional, table) Parameters to send to the server ---@param handler (optional, functionnil) See |lsp-handler|. Follows |lsp-handler-resolution| +---@param method (string) LSP method name +---@param params (optional, table) Parameters to send to the server +---@param handler (optional, functionnil) See |lsp-handler|. Follows |lsp-handler-resolution| -- ---@returns 2-tuple: +---@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. --- ---@see |vim.lsp.buf_request()| +---@see |vim.lsp.buf_request()| local function request(method, params, handler) validate { method = {method, 's'}; @@ -49,7 +49,7 @@ end --- Checks whether the language servers attached to the current buffer are --- ready. --- ---@returns `true` if server responds. +---@returns `true` if server responds. function M.server_ready() return not not vim.lsp.buf_notify(0, "window/progress", {}) end @@ -62,7 +62,7 @@ function M.hover() end --- Jumps to the declaration of the symbol under the cursor. ---@note Many servers do not implement this method. Generally, see |vim.lsp.buf.definition()| instead. +---@note Many servers do not implement this method. Generally, see |vim.lsp.buf.definition()| instead. --- function M.declaration() local params = util.make_position_params() @@ -100,22 +100,22 @@ 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 (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.constants.CompletionTriggerKind| function M.completion(context) local params = util.make_position_params() params.context = context return request('textDocument/completion', params) end ---@private +---@private --- If there is more than one client that supports the given method, --- asks the user to select one. -- ---@returns The client that the user selected or nil +---@returns The client that the user selected or nil local function select_client(method) local clients = vim.tbl_values(vim.lsp.buf_get_clients()); clients = vim.tbl_filter(function (client) @@ -146,11 +146,11 @@ end --- Formats the current buffer. --- ---@param options (optional, table) Can be used to specify FormattingOptions. +---@param options (optional, table) 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/specification#textDocument_formatting +---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting function M.formatting(options) local client = select_client("textDocument/formatting") if client == nil then return end @@ -168,9 +168,9 @@ end --- vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()]] --- </pre> --- ---@param options Table with valid `FormattingOptions` entries ---@param timeout_ms (number) Request timeout ---@see |vim.lsp.buf.formatting_seq_sync| +---@param options Table with valid `FormattingOptions` entries +---@param timeout_ms (number) Request timeout +---@see |vim.lsp.buf.formatting_seq_sync| function M.formatting_sync(options, timeout_ms) local client = select_client("textDocument/formatting") if client == nil then return end @@ -195,9 +195,9 @@ end --- vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] --- </pre> --- ---@param options (optional, table) `FormattingOptions` entries ---@param timeout_ms (optional, number) Request timeout ---@param order (optional, table) List of client names. Formatting is requested from clients +---@param options (optional, table) `FormattingOptions` entries +---@param timeout_ms (optional, number) Request timeout +---@param order (optional, table) List of client names. Formatting is requested from clients ---in the following order: first all clients that are not in the `order` list, then ---the remaining clients in the order as they occur in the `order` list. function M.formatting_seq_sync(options, timeout_ms, order) @@ -230,10 +230,10 @@ end --- Formats a given range. --- ---@param options Table with valid `FormattingOptions` entries. ---@param start_pos ({number, number}, optional) mark-indexed position. +---@param options Table with valid `FormattingOptions` entries. +---@param start_pos ({number, number}, optional) mark-indexed position. ---Defaults to the start of the last visual selection. ---@param end_pos ({number, number}, optional) mark-indexed position. +---@param end_pos ({number, number}, optional) mark-indexed position. ---Defaults to the end of the last visual selection. function M.range_formatting(options, start_pos, end_pos) local client = select_client("textDocument/rangeFormatting") @@ -246,7 +246,7 @@ end --- Renames all references to the symbol under the cursor. --- ---@param new_name (string) If not provided, the user will be prompted for a new +---@param new_name (string) If not provided, the user will be prompted for a new ---name using |input()|. function M.rename(new_name) -- TODO(ashkan) use prepareRename @@ -260,8 +260,8 @@ end --- Lists all the references to the symbol under the cursor in the quickfix window. --- ---@param context (table) Context for the request ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references +---@param context (table) Context for the request +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references function M.references(context) validate { context = { context, 't', true } } local params = util.make_position_params() @@ -279,7 +279,7 @@ function M.document_symbol() request('textDocument/documentSymbol', params) end ---@private +---@private local function pick_call_hierarchy_item(call_hierarchy_items) if not call_hierarchy_items then return end if #call_hierarchy_items == 1 then @@ -297,7 +297,7 @@ local function pick_call_hierarchy_item(call_hierarchy_items) return choice end ---@private +---@private local function call_hierarchy(method) local params = util.make_position_params() request('textDocument/prepareCallHierarchy', params, function(err, _, result) @@ -389,7 +389,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, optional) function M.workspace_symbol(query) query = query or npcall(vfn.input, "Query: ") local params = {query = query} @@ -424,7 +424,7 @@ end --- Requests code actions from all clients and calls the handler exactly once --- with all aggregated results ---@private +---@private local function code_action_request(params) local bufnr = vim.api.nvim_get_current_buf() local method = 'textDocument/codeAction' @@ -439,9 +439,9 @@ end --- Selects a code action from the input list that is available at the current --- cursor position. --- ---@param context: (table, optional) Valid `CodeActionContext` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction +--- +---@param context: (table, optional) Valid `CodeActionContext` object +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction function M.code_action(context) validate { context = { context, 't', true } } context = context or { diagnostics = vim.lsp.diagnostic.get_line_diagnostics() } @@ -452,10 +452,10 @@ end --- Performs |vim.lsp.buf.code_action()| for a given range. --- ---@param context: (table, optional) Valid `CodeActionContext` object ---@param start_pos ({number, number}, optional) mark-indexed position. +---@param context: (table, optional) Valid `CodeActionContext` object +---@param start_pos ({number, number}, optional) mark-indexed position. ---Defaults to the start of the last visual selection. ---@param end_pos ({number, number}, optional) mark-indexed position. +---@param end_pos ({number, number}, optional) mark-indexed position. ---Defaults to the end of the last visual selection. function M.range_code_action(context, start_pos, end_pos) validate { context = { context, 't', true } } @@ -467,8 +467,8 @@ end --- Executes an LSP server command. --- ---@param command A valid `ExecuteCommandParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand +---@param command A valid `ExecuteCommandParams` object +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand function M.execute_command(command) validate { command = { command.command, 's' }, diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index fe581e42ad..ca5a44077e 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -22,11 +22,11 @@ local namespaces = setmetatable({}, { end; }) ---@private +---@private M.__namespaces = namespaces ---@private +---@private local function execute_lens(lens, bufnr, client_id) local line = lens.range.start.line api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) @@ -151,7 +151,7 @@ function M.save(lenses, bufnr, client_id) end ---@private +---@private local function resolve_lenses(lenses, bufnr, client_id, callback) lenses = lenses or {} local num_lens = vim.tbl_count(lenses) @@ -160,7 +160,7 @@ local function resolve_lenses(lenses, bufnr, client_id, callback) return end - --@private + ---@private local function countdown() num_lens = num_lens - 1 if num_lens == 0 then diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index a244e3d6a4..45aeb17465 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -8,7 +8,7 @@ local util = require('vim.lsp.util') local if_nil = vim.F.if_nil ---@class DiagnosticSeverity +---@class DiagnosticSeverity local DiagnosticSeverity = protocol.DiagnosticSeverity local to_severity = function(severity) @@ -46,14 +46,14 @@ end ---@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[] +---@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 M = {} @@ -167,12 +167,12 @@ end local _diagnostic_namespaces = _make_namespace_table("vim_lsp_diagnostics", true) local _sign_namespaces = _make_namespace_table("vim_lsp_signs", false) ---@private +---@private function M._get_diagnostic_namespace(client_id) return _diagnostic_namespaces[client_id] end ---@private +---@private function M._get_sign_namespace(client_id) return _sign_namespaces[client_id] end @@ -255,7 +255,7 @@ local _diagnostic_counts = function(diagnostics) return counts end ---@private +---@private --- Set the different diagnostic cache after `textDocument/publishDiagnostics` ---@param diagnostics Diagnostic[] ---@param bufnr number @@ -291,7 +291,7 @@ local function set_diagnostic_cache(diagnostics, bufnr, client_id) end ---@private +---@private --- Clear the cached diagnostics ---@param bufnr number ---@param client_id number @@ -512,7 +512,7 @@ local _next_diagnostic = function(position, search_forward, bufnr, opts, client_ end end ---@private +---@private --- Helper function to return a position from a diagnostic --- ---@return table {row, col} @@ -527,7 +527,7 @@ local function _diagnostic_pos(opts, diagnostic) return to_position(diagnostic.range.start, bufnr) end ---@private +---@private -- Move to the diagnostic position local function _diagnostic_move_pos(name, opts, pos) opts = opts or {} @@ -858,7 +858,7 @@ end --- Callback scheduled for after leaving insert mode --- --- Used to handle ---@private +---@private function M._execute_scheduled_display(bufnr, client_id) local args = _bufs_waiting_to_update[bufnr][client_id] if not args then @@ -924,20 +924,20 @@ end -- Diagnostic Private Highlight Utilies {{{ --- Get the severity highlight name ---@private +---@private function M._get_severity_highlight_name(severity) return virtual_text_highlight_map[severity] end --- Get floating severity highlight name ---@private +---@private function M._get_floating_severity_highlight_name(severity) return floating_highlight_map[severity] end --- This should be called to update the highlights for the LSP client. function M._define_default_signs_and_highlights() - --@private + ---@private local function define_default_sign(name, properties) if vim.tbl_isempty(vim.fn.sign_getdefined(name)) then vim.fn.sign_define(name, properties) @@ -1054,8 +1054,8 @@ function M.on_publish_diagnostics(_, _, params, client_id, _, config) end -- restores the extmarks set by M.display ---- @param last number last line that was changed --- @private +---@param last number last line that was changed +---@private local function restore_extmarks(bufnr, last) for client_id, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do local ns = M._get_diagnostic_namespace(client_id) @@ -1084,7 +1084,7 @@ local function restore_extmarks(bufnr, last) end -- caches the extmarks set by M.display --- @private +---@private local function save_extmarks(bufnr, client_id) bufnr = bufnr == 0 and api.nvim_get_current_buf() or bufnr if not diagnostic_attached_buffers[bufnr] then @@ -1101,7 +1101,7 @@ local function save_extmarks(bufnr, client_id) diagnostic_cache_extmarks[bufnr][client_id] = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, {details = true}) end ---@private +---@private --- Display diagnostics for the buffer, given a configuration. function M.display(diagnostics, bufnr, client_id, config) if diagnostic_disabled[bufnr][client_id] then @@ -1187,10 +1187,10 @@ end --- for redrawing diagnostics after making changes in diagnostics --- configuration. |lsp-handler-configuration| --- ---- @param bufnr (optional, number): Buffer handle, defaults to current ---- @param client_id (optional, number): Redraw diagnostics for the given ---- client. The default is to redraw diagnostics for all attached ---- clients. +---@param bufnr (optional, number): Buffer handle, defaults to current +---@param client_id (optional, number): Redraw diagnostics for the given +--- client. The default is to redraw diagnostics for all attached +--- clients. function M.redraw(bufnr, client_id) bufnr = get_bufnr(bufnr) if not client_id then @@ -1410,10 +1410,10 @@ function M.set_loclist(opts) end --- Disable diagnostics for the given buffer and client ---- @param bufnr (optional, number): Buffer handle, defaults to current ---- @param client_id (optional, number): Disable diagnostics for the given ---- client. The default is to disable diagnostics for all attached ---- clients. +---@param bufnr (optional, number): Buffer handle, defaults to current +---@param client_id (optional, number): Disable diagnostics for the given +--- client. The default is to disable diagnostics for all attached +--- clients. -- Note that when diagnostics are disabled for a buffer, the server will still -- send diagnostic information and the client will still process it. The -- diagnostics are simply not displayed to the user. @@ -1429,10 +1429,10 @@ function M.disable(bufnr, client_id) end --- Enable diagnostics for the given buffer and client ---- @param bufnr (optional, number): Buffer handle, defaults to current ---- @param client_id (optional, number): Enable diagnostics for the given ---- client. The default is to enable diagnostics for all attached ---- clients. +---@param bufnr (optional, number): Buffer handle, defaults to current +---@param client_id (optional, number): Enable diagnostics for the given +--- client. The default is to enable diagnostics for all attached +--- clients. function M.enable(bufnr, client_id) if not client_id then return vim.lsp.for_each_buffer_client(bufnr, function(client) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index b7f1ea0ab6..befb9fcec3 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -9,9 +9,9 @@ local M = {} -- FIXME: DOC: Expose in vimdocs ---@private +---@private --- Writes to error buffer. ---@param ... (table of strings) Will be concatenated before being written +---@param ... (table of strings) 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") @@ -22,7 +22,7 @@ M['workspace/executeCommand'] = function() -- Error handling is done implicitly by wrapping all handlers; see end of this file end ---@private +---@private local function progress_handler(_, _, params, 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) @@ -189,7 +189,7 @@ end ---@private +---@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 @@ -197,8 +197,8 @@ 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 entity name of the resource used in a `not found` error message +---@param map_result function `((resp, bufnr) -> list)` to convert the response +---@param entity name of the resource used in a `not found` error message local function response_to_list(map_result, entity) return function(_, _, result, _, bufnr, config) if not result or vim.tbl_isempty(result) then @@ -289,11 +289,11 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover M['textDocument/hover'] = M.hover ---@private +---@private --- Jumps to a location. Used as a handler for multiple LSP methods. ---@param _ (not used) ---@param method (string) LSP method name ---@param result (table) result of LSP method; a location or a list of locations. +---@param _ (not used) +---@param method (string) LSP method name +---@param result (table) result of LSP method; a location or a list of locations. ---(`textDocument/definition` can return `Location` or `Location[]` local function location_handler(_, method, result) if result == nil or vim.tbl_isempty(result) then @@ -377,13 +377,13 @@ M['textDocument/documentHighlight'] = function(_, _, result, _, bufnr, _) util.buf_highlight_references(bufnr, result) end ---@private +---@private --- --- 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"`, +---@param direction `"from"` for incoming calls and `"to"` for outgoing calls +---@returns `CallHierarchyIncomingCall[]` if {direction} is `"from"`, +---@returns `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, local make_call_hierarchy_handler = function(direction) return function(_, _, result) if not result then return end diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index 73fafb9715..a2d5c3a774 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -18,14 +18,14 @@ local log_date_format = "%FT%H:%M:%S%z" do local path_sep = vim.loop.os_uname().version:match("Windows") and "\\" or "/" - --@private + ---@private local function path_join(...) return table.concat(vim.tbl_flatten{...}, path_sep) end local logfilename = path_join(vim.fn.stdpath('cache'), 'lsp.log') --- Returns the log filename. - --@returns (string) log filename + ---@returns (string) log filename function log.get_filename() return logfilename end @@ -77,7 +77,7 @@ end vim.tbl_add_reverse_lookup(log.levels) --- Sets the current log level. ---@param level (string or number) One of `vim.lsp.log.levels` +---@param level (string or number) One of `vim.lsp.log.levels` function log.set_level(level) if type(level) == 'string' then current_log_level = assert(log.levels[level:upper()], string.format("Invalid log level: %q", level)) @@ -89,8 +89,8 @@ function log.set_level(level) end --- Checks whether the level is sufficient for logging. ---@param level number log level ---@returns (bool) true if would log, false if not +---@param level number log level +---@returns (bool) true if would log, false if not function log.should_log(level) return level >= current_log_level end diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 6d02b9ba74..ded8af5773 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -5,14 +5,14 @@ local if_nil = vim.F.if_nil local protocol = {} --[=[ ---@private +---@private --- Useful for interfacing with: --- https://github.com/microsoft/language-server-protocol/raw/gh-pages/_specifications/specification-3-14.md function transform_schema_comments() nvim.command [[silent! '<,'>g/\/\*\*\|\*\/\|^$/d]] nvim.command [[silent! '<,'>s/^\(\s*\) \* \=\(.*\)/\1--\2/]] end ---@private +---@private function transform_schema_to_table() transform_schema_comments() nvim.command [[silent! '<,'>s/: \S\+//]] diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 4c5f02af9d..eedb708118 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -5,11 +5,11 @@ local protocol = require('vim.lsp.protocol') local validate, schedule, schedule_wrap = vim.validate, vim.schedule, vim.schedule_wrap -- TODO replace with a better implementation. ---@private +---@private --- Encodes to JSON. --- ---@param data (table) Data to encode ---@returns (string) Encoded object +---@param data (table) Data to encode +---@returns (string) Encoded object local function json_encode(data) local status, result = pcall(vim.fn.json_encode, data) if status then @@ -18,11 +18,11 @@ local function json_encode(data) return nil, result end end ---@private +---@private --- Decodes from JSON. --- ---@param data (string) Data to decode ---@returns (table) Decoded JSON object +---@param data (string) Data to decode +---@returns (table) Decoded JSON object local function json_decode(data) local status, result = pcall(vim.fn.json_decode, data) if status then @@ -32,10 +32,10 @@ local function json_decode(data) end end ---@private +---@private --- Checks whether a given path exists and is a directory. ---@param filename (string) path to check ---@returns (bool) +---@param filename (string) path to check +---@returns (bool) local function is_dir(filename) local stat = vim.loop.fs_stat(filename) return stat and stat.type == 'directory' or false @@ -43,7 +43,7 @@ end local NIL = vim.NIL ---@private +---@private local recursive_convert_NIL recursive_convert_NIL = function(v, tbl_processed) if v == NIL then @@ -63,15 +63,15 @@ recursive_convert_NIL = function(v, tbl_processed) return v end ---@private +---@private --- Returns its argument, but converts `vim.NIL` to Lua `nil`. ---@param v (any) Argument ---@returns (any) +---@param v (any) Argument +---@returns (any) local function convert_NIL(v) return recursive_convert_NIL(v, {}) end ---@private +---@private --- Merges current process env with the given env and returns the result as --- a list of "k=v" strings. --- @@ -81,8 +81,8 @@ end --- 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 +---@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 @@ -97,11 +97,11 @@ local function env_merge(env) return final_env end ---@private +---@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 +---@param encoded_message (string) +---@returns (table) table containing encoded message and `Content-Length` attribute local function format_message_with_content_length(encoded_message) return table.concat { 'Content-Length: '; tostring(#encoded_message); '\r\n\r\n'; @@ -109,11 +109,11 @@ local function format_message_with_content_length(encoded_message) } end ---@private +---@private --- Parses an LSP Message's header --- ---@param header: The header to parse. ---@returns Parsed headers +---@param header: The header to parse. +---@returns Parsed headers local function parse_headers(header) if type(header) ~= 'string' then return nil @@ -141,7 +141,7 @@ end -- case insensitive pattern. local header_start_pattern = ("content"):gsub("%w", function(c) return "["..c..c:upper().."]" end) ---@private +---@private --- The actual workhorse. local function request_parser_loop() local buffer = '' -- only for header part @@ -203,8 +203,8 @@ local client_errors = vim.tbl_add_reverse_lookup { --- Constructs an error message from an LSP error object. --- ---@param err (table) The error object ---@returns (string) The formatted error message +---@param err (table) The error object +---@returns (string) The formatted error message local function format_rpc_error(err) validate { err = { err, 't' }; @@ -233,9 +233,9 @@ end --- Creates an RPC response object/table. --- ---@param code RPC error code defined in `vim.lsp.protocol.ErrorCodes` ---@param message (optional) arbitrary message to send to server ---@param data (optional) arbitrary data to send to server +---@param code RPC error code defined in `vim.lsp.protocol.ErrorCodes` +---@param message (optional) arbitrary message to send to server +---@param data (optional) arbitrary data to send to server local function 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') @@ -250,38 +250,38 @@ end local default_dispatchers = {} ---@private +---@private --- Default dispatcher for notifications sent to an LSP server. --- ---@param method (string) The invoked LSP method ---@param params (table): Parameters for the invoked LSP method +---@param method (string) The invoked LSP method +---@param params (table): Parameters for the invoked LSP method function default_dispatchers.notification(method, params) local _ = log.debug() and log.debug('notification', method, params) end ---@private +---@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`. +---@param method (string) The invoked LSP method +---@param params (table): Parameters for the invoked LSP method +---@returns `nil` and `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) end ---@private +---@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 (number): Exit code +---@param signal (number): 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 +---@private --- Default dispatcher for client errors. --- ---@param code (number): Error code ---@param err (any): Details about the error +---@param code (number): 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) @@ -290,25 +290,25 @@ end --- Starts an LSP server process and create an LSP RPC client object to --- interact with it. --- ---@param cmd (string) Command to start the LSP server. ---@param cmd_args (table) List of additional string arguments to pass to {cmd}. ---@param dispatchers (table, optional) Dispatchers for LSP message types. Valid +---@param cmd (string) Command to start the LSP server. +---@param cmd_args (table) List of additional string arguments to pass to {cmd}. +---@param dispatchers (table, optional) Dispatchers for LSP message types. Valid ---dispatcher names are: --- - `"notification"` --- - `"server_request"` --- - `"on_error"` --- - `"on_exit"` ---@param extra_spawn_params (table, optional) Additional context for the LSP +---@param extra_spawn_params (table, optional) Additional context for the LSP --- 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 Client RPC object. --- ---@returns Methods: +---@returns Methods: --- - `notify()` |vim.lsp.rpc.notify()| --- - `request()` |vim.lsp.rpc.request()| --- ---@returns Members: +---@returns Members: --- - {pid} (number) The LSP server's PID. --- - {handle} A handle for low-level interaction with the LSP server process --- |vim.loop|. @@ -358,10 +358,10 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local handle, pid do - --@private + ---@private --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. - --@param code (number) Exit code - --@param signal (number) Signal that was used to terminate (if any) + ---@param code (number) Exit code + ---@param signal (number) Signal that was used to terminate (if any) local function onexit(code, signal) stdin:close() stdout:close() @@ -385,12 +385,12 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end end - --@private + ---@private --- Encodes {payload} into a JSON-RPC message and sends it to the remote --- process. --- - --@param payload (table) Converted into a JSON string, see |json_encode()| - --@returns true if the payload could be scheduled, false if the main event-loop is in the process of closing. + ---@param payload (table) Converted into a JSON string, see |json_encode()| + ---@returns true if the payload could be scheduled, false if the main event-loop is in the process of closing. local function encode_and_send(payload) local _ = log.debug() and log.debug("rpc.send.payload", payload) if handle == nil or handle:is_closing() then return false end @@ -406,9 +406,9 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) -- `start()` -- --- Sends a notification to the LSP server. - --@param method (string) The invoked LSP method - --@param params (table): Parameters for the invoked LSP method - --@returns (bool) `true` if notification could be sent, `false` if not + ---@param method (string) The invoked LSP method + ---@param params (table): Parameters for the invoked LSP method + ---@returns (bool) `true` if notification could be sent, `false` if not local function notify(method, params) return encode_and_send { jsonrpc = "2.0"; @@ -417,7 +417,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) } end - --@private + ---@private --- sends an error object to the remote LSP process. local function send_response(request_id, err, result) return encode_and_send { @@ -433,10 +433,10 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) -- --- Sends a request to the LSP server and runs {callback} upon response. --- - --@param method (string) The invoked LSP method - --@param params (table) Parameters for the invoked LSP method - --@param callback (function) Callback to invoke - --@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not + ---@param method (string) The invoked LSP method + ---@param params (table) Parameters for the invoked LSP method + ---@param callback (function) Callback to invoke + ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not local function request(method, params, callback) validate { callback = { callback, 'f' }; @@ -463,13 +463,13 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end end) - --@private + ---@private local function on_error(errkind, ...) assert(client_errors[errkind]) -- TODO what to do if this fails? pcall(dispatchers.on_error, errkind, ...) end - --@private + ---@private local function pcall_handler(errkind, status, head, ...) if not status then on_error(errkind, head, ...) @@ -477,7 +477,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end return status, head, ... end - --@private + ---@private local function try_call(errkind, fn, ...) return pcall_handler(errkind, pcall(fn, ...)) end @@ -486,7 +486,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) -- time and log them. This would require storing the timestamp. I could call -- them with an error then, perhaps. - --@private + ---@private local function handle_body(body) local decoded, err = json_decode(body) if not decoded then diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index d682fdc17e..a4b3298fd8 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -40,10 +40,10 @@ local loclist_type_map = { } ---@private --- Check the border given by opts or the default border for the additional --- size it adds to a float. ---@returns size of border in height and width +---@private +--- Check the border given by opts or the default border for the additional +--- size it adds to a float. +---@returns size of border in height and width local function get_border_size(opts) local border = opts and opts.border or default_border local height = 0 @@ -86,7 +86,7 @@ local function get_border_size(opts) return { height = height, width = width } end ---@private +---@private local function split_lines(value) return split(value, '\n', true) end @@ -95,11 +95,11 @@ end --- --- CAUTION: Changes in-place! --- ---@param lines (table) Original list of strings ---@param A (table) Start position; a 2-tuple of {line, col} numbers ---@param B (table) End position; a 2-tuple of {line, col} numbers ---@param new_lines A list of strings to replace the original ---@returns (table) The modified {lines} object +---@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 function M.set_lines(lines, A, B, new_lines) -- 0-indexing to 1-indexing local i_0 = A[1] + 1 @@ -133,7 +133,7 @@ function M.set_lines(lines, A, B, new_lines) return lines end ---@private +---@private local function sort_by_key(fn) return function(a,b) local ka, kb = fn(a), fn(b) @@ -147,12 +147,12 @@ local function sort_by_key(fn) return false end end ---@private +---@private local edit_sort_key = sort_by_key(function(e) return {e.A[1], e.A[2], e.i} end) ---@private +---@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 --- 1-indexed @@ -238,8 +238,8 @@ function M.get_progress_messages() end --- Applies a list of text edits to a buffer. ---@param text_edits (table) list of `TextEdit` objects ---@param buf_nr (number) Buffer id +---@param text_edits (table) list of `TextEdit` objects +---@param buf_nr (number) Buffer id ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit function M.apply_text_edits(text_edits, bufnr) if not next(text_edits) then return end @@ -295,11 +295,11 @@ end -- function M.glob_to_regex(glob) -- end ---@private +---@private --- Finds the first line and column of the difference between old and new lines ---@param old_lines table list of lines ---@param new_lines table list of lines ---@returns (int, int) start_line_idx and start_col_idx of range +---@param old_lines table list of lines +---@param new_lines table list of lines +---@returns (int, int) start_line_idx and start_col_idx of range local function first_difference(old_lines, new_lines, start_line_idx) local line_count = math.min(#old_lines, #new_lines) if line_count == 0 then return 1, 1 end @@ -325,12 +325,12 @@ local function first_difference(old_lines, new_lines, start_line_idx) end ---@private +---@private --- Finds the last line and column of the differences between old and new lines ---@param old_lines table list of lines ---@param new_lines table list of lines ---@param start_char integer First different character idx of range ---@returns (int, int) end_line_idx and end_col_idx of range +---@param old_lines table list of lines +---@param new_lines table list of lines +---@param start_char integer First different character idx of range +---@returns (int, int) end_line_idx and end_col_idx of range local function last_difference(old_lines, new_lines, start_char, end_line_idx) local line_count = math.min(#old_lines, #new_lines) if line_count == 0 then return 0,0 end @@ -369,14 +369,14 @@ local function last_difference(old_lines, new_lines, start_char, end_line_idx) end ---@private +---@private --- Get the text of the range defined by start and end line/column ---@param lines table list of lines ---@param start_char integer First different character idx of range ---@param end_char integer Last different character idx of range ---@param start_line integer First different line idx of range ---@param end_line integer Last different line idx of range ---@returns string text extracted from defined region +---@param lines table list of lines +---@param start_char integer First different character idx of range +---@param end_char integer Last different character idx of range +---@param start_line integer First different line idx of range +---@param end_line integer Last different line idx of range +---@returns string text extracted from defined region local function extract_text(lines, start_line, start_char, end_line, end_char) if start_line == #lines + end_line + 1 then if end_line == 0 then return '' end @@ -396,14 +396,14 @@ local function extract_text(lines, start_line, start_char, end_line, end_char) return result end ---@private +---@private --- Compute the length of the substituted range ---@param lines table list of lines ---@param start_char integer First different character idx of range ---@param end_char integer Last different character idx of range ---@param start_line integer First different line idx of range ---@param end_line integer Last different line idx of range ---@returns (int, int) end_line_idx and end_col_idx of range +---@param lines table list of lines +---@param start_char integer First different character idx of range +---@param end_char integer Last different character idx of range +---@param start_line integer First different line idx of range +---@param end_line integer Last different line idx of range +---@returns (int, int) end_line_idx and end_col_idx of range local function compute_length(lines, start_line, start_char, end_line, end_char) local adj_end_line = #lines + end_line + 1 local adj_end_char @@ -424,12 +424,12 @@ local function compute_length(lines, start_line, start_char, end_line, end_char) end --- Returns the range table for the difference between old and new lines ---@param old_lines table list of lines ---@param new_lines table list of lines ---@param start_line_idx int line to begin search for first difference ---@param end_line_idx int line to begin search for last difference ---@param offset_encoding string encoding requested by language server ---@returns table start_line_idx and start_col_idx of range +---@param old_lines table list of lines +---@param new_lines table list of lines +---@param start_line_idx int line to begin search for first difference +---@param end_line_idx int line to begin search for last difference +---@param offset_encoding string encoding requested by language server +---@returns table start_line_idx and start_col_idx of range function M.compute_diff(old_lines, new_lines, start_line_idx, end_line_idx, offset_encoding) local start_line, start_char = first_difference(old_lines, new_lines, start_line_idx) local end_line, end_char = last_difference(vim.list_slice(old_lines, start_line, #old_lines), @@ -469,9 +469,9 @@ 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 ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion +---@param result (table) The result of a `textDocument/completion` request +---@returns (table) List of completion items +---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion function M.extract_completion_items(result) if type(result) == 'table' and result.items then -- result is a `CompletionList` @@ -515,12 +515,12 @@ function M.apply_text_document_edit(text_document_edit, index) M.apply_text_edits(text_document_edit.edits, bufnr) end ---@private +---@private --- Recursively parses snippets in a completion entry. --- ---@param input (string) Snippet text to parse for snippets ---@param inner (bool) Whether this function is being called recursively ---@returns 2-tuple of strings: The first is the parsed result, the second is the +---@param input (string) Snippet text to parse for snippets +---@param inner (bool) Whether this function is being called recursively +---@returns 2-tuple of strings: The first is the parsed result, the second is the ---unparsed rest of the input local function parse_snippet_rec(input, inner) local res = "" @@ -577,28 +577,28 @@ end --- Parses snippets in a completion entry. --- ---@param input (string) unparsed snippet ---@returns (string) parsed snippet +---@param input (string) unparsed snippet +---@returns (string) parsed snippet function M.parse_snippet(input) local res, _ = parse_snippet_rec(input, false) return res end ---@private +---@private --- Sorts by CompletionItem.sortText. --- ---@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 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 +---@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 +--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] @@ -618,7 +618,7 @@ local function get_completion_word(item) return item.label end ---@private +---@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. @@ -633,9 +633,9 @@ end --- 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 +---@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" end @@ -643,12 +643,12 @@ end --- Turns the result of a `textDocument/completion` request into vim-compatible --- |complete-items|. --- ---@param result The result of a `textDocument/completion` call, e.g. from +---@param result 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| +---@param prefix (string) the prefix to filter the completion items +---@returns { matches = complete-items table, incomplete = bool } +---@see |complete-items| function M.text_document_completion_list_to_complete_items(result, prefix) local items = M.extract_completion_items(result) if vim.tbl_isempty(items) then @@ -698,8 +698,8 @@ end --- Rename old_fname to new_fname --- ---@param opts (table) +--- +---@param opts (table) -- overwrite? bool -- ignoreIfExists? bool function M.rename(old_fname, new_fname, opts) @@ -754,8 +754,8 @@ end --- Applies a `WorkspaceEdit`. --- ---@param workspace_edit (table) `WorkspaceEdit` --- @see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit +---@param workspace_edit (table) `WorkspaceEdit` +--see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit function M.apply_workspace_edit(workspace_edit) if workspace_edit.documentChanges then for idx, change in ipairs(workspace_edit.documentChanges) do @@ -794,10 +794,10 @@ end --- window for `textDocument/hover`, for parsing the result of --- `textDocument/signatureHelp`, and potentially others. --- ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param contents (table, optional, default `{}`) List of strings to extend with converted lines ---@returns {contents}, extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover +---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) +---@param contents (table, optional, default `{}`) List of strings to extend with converted lines +---@returns {contents}, extended with lines of converted markdown. +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover function M.convert_input_to_markdown_lines(input, contents) contents = contents or {} -- MarkedString variation 1 @@ -844,11 +844,11 @@ end --- Converts `textDocument/SignatureHelp` response to markdown lines. --- ---@param signature_help Response of `textDocument/SignatureHelp` ---@param ft optional filetype that will be use as the `lang` for the label markdown code block ---@param triggers optional list of trigger characters from the lsp server. used to better determine parameter offsets ---@returns list of lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp +---@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. +---@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 return @@ -943,10 +943,10 @@ 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) ---@returns (table) Options +---@param width (number) window width (in character cells) +---@param height (number) window height (in character cells) +---@param opts (table, optional) +---@returns (table) Options function M.make_floating_popup_options(width, height, opts) validate { opts = { opts, 't', true }; @@ -997,8 +997,8 @@ end --- Jumps to a location. --- ---@param location (`Location`|`LocationLink`) ---@returns `true` if the jump succeeded +---@param location (`Location`|`LocationLink`) +---@returns `true` if the jump succeeded function M.jump_to_location(location) -- location may be Location or LocationLink local uri = location.uri or location.targetUri @@ -1028,8 +1028,8 @@ 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 a single `Location` or `LocationLink` +---@returns (bufnr,winnr) buffer and window number of floating window or nil function M.preview_location(location, opts) -- location may be LocationLink or Location (more useful for the former) local uri = location.targetUri or location.uri @@ -1052,7 +1052,7 @@ function M.preview_location(location, opts) return M.open_floating_preview(contents, syntax, opts) end ---@private +---@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 @@ -1088,10 +1088,10 @@ function M._trim(contents, opts) return contents 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 +--- 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 @@ -1227,7 +1227,7 @@ function M.stylize_markdown(bufnr, contents, opts) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped) local idx = 1 - --@private + ---@private -- keep track of syntaxes we already inlcuded. -- no need to include the same syntax more than once local langs = {} @@ -1276,26 +1276,26 @@ end --- Creates autocommands to close a preview window when events happen. --- ---@param events (table) list of events ---@param winnr (number) window id of preview window ---@see |autocmd-events| +---@param events (table) list of events +---@param winnr (number) window id of preview window +---@see |autocmd-events| function M.close_preview_autocmd(events, winnr) if #events > 0 then api.nvim_command("autocmd "..table.concat(events, ',').." <buffer> ++once lua pcall(vim.api.nvim_win_close, "..winnr..", true)") end end ---@internal +---@internal --- 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 --- - 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 +---@param contents table of lines to show in window +---@param opts dictionary 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 function M._make_floating_popup_size(contents, opts) validate { contents = { contents, 't' }; @@ -1362,9 +1362,9 @@ end --- Shows contents in a floating window. --- ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ---@param opts dictionary with optional fields +---@param contents table of lines to show in window +---@param syntax string of syntax to set for opened buffer +---@param opts dictionary with optional fields --- - height of floating window --- - width of floating window --- - wrap boolean enable wrapping of long lines (defaults to true) @@ -1378,7 +1378,7 @@ end --- - focus_id if a popup with this id is opened, then focus it --- - close_events list of events that closes the floating window --- - focusable (boolean, default true): Make float focusable ---@returns bufnr,winnr buffer and window number of the newly created floating +---@returns bufnr,winnr buffer and window number of the newly created floating ---preview window function M.open_floating_preview(contents, syntax, opts) validate { @@ -1474,7 +1474,7 @@ do --[[ References ]] --- Removes document highlights from a buffer. --- - --@param bufnr buffer id + ---@param bufnr buffer id function M.buf_clear_references(bufnr) validate { bufnr = {bufnr, 'n', true} } api.nvim_buf_clear_namespace(bufnr, reference_ns, 0, -1) @@ -1482,8 +1482,8 @@ do --[[ References ]] --- Shows a list of document highlights for a certain buffer. --- - --@param bufnr buffer id - --@param references List of `DocumentHighlight` objects to highlight + ---@param bufnr buffer id + ---@param references List of `DocumentHighlight` objects to highlight ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight function M.buf_highlight_references(bufnr, references) validate { bufnr = {bufnr, 'n', true} } @@ -1505,24 +1505,24 @@ local position_sort = sort_by_key(function(v) return {v.start.line, v.start.character} end) --- Gets the zero-indexed line from the given uri. +--- Gets the zero-indexed line from the given uri. +---@param uri string uri of the resource to get the line from +---@param row number zero-indexed line number +---@return string the line at row in filename -- For non-file uris, we load the buffer and get the line. -- If a loaded buffer exists, then that is used. -- Otherwise we get the line using libuv which is a lot faster than loading the buffer. ---@param uri string uri of the resource to get the line from ---@param row number zero-indexed line number ---@return string the line at row in filename function M.get_line(uri, row) return M.get_lines(uri, { row })[row] end --- Gets the zero-indexed lines from the given uri. +--- Gets the zero-indexed lines from the given uri. +---@param uri string uri of the resource to get the lines from +---@param rows number[] zero-indexed line numbers +---@return table<number string> a table mapping rows to lines -- For non-file uris, we load the buffer and get the lines. -- If a loaded buffer exists, then that is used. -- Otherwise we get the lines using libuv which is a lot faster than loading the buffer. ---@param uri string uri of the resource to get the lines from ---@param rows number[] zero-indexed line numbers ---@return table<number string> a table mapping rows to lines function M.get_lines(uri, rows) rows = type(rows) == "table" and rows or { rows } @@ -1590,8 +1590,8 @@ end --- Returns the items with the byte position calculated correctly and in sorted --- order, for display in quickfix and location lists. --- ---@param locations (table) list of `Location`s or `LocationLink`s ---@returns (table) list of items +---@param locations (table) list of `Location`s or `LocationLink`s +---@returns (table) list of items function M.locations_to_items(locations) local items = {} local grouped = setmetatable({}, { @@ -1648,7 +1648,7 @@ end --- Can be obtained with e.g. |vim.lsp.util.locations_to_items()|. --- Defaults to current window. --- ---@param items (table) list of items +---@param items (table) list of items function M.set_loclist(items, win_id) vim.fn.setloclist(win_id or 0, {}, ' ', { title = 'Language Server'; @@ -1659,7 +1659,7 @@ end --- Fills quickfix list with given list of items. --- Can be obtained with e.g. |vim.lsp.util.locations_to_items()|. --- ---@param items (table) list of items +---@param items (table) list of items function M.set_qflist(items) vim.fn.setqflist({}, ' ', { title = 'Language Server'; @@ -1676,9 +1676,9 @@ end --- Converts symbols to quickfix list items. --- ---@param symbols DocumentSymbol[] or SymbolInformation[] +---@param symbols DocumentSymbol[] or SymbolInformation[] function M.symbols_to_items(symbols, bufnr) - --@private + ---@private local function _symbols_to_items(_symbols, _items, _bufnr) for _, symbol in ipairs(_symbols) do if symbol.location then -- SymbolInformation type @@ -1714,8 +1714,8 @@ function M.symbols_to_items(symbols, bufnr) end --- Removes empty lines from the beginning and end. ---@param lines (table) list of lines to trim ---@returns (table) trimmed list of lines +---@param lines (table) list of lines to trim +---@returns (table) trimmed list of lines function M.trim_empty_lines(lines) local start = 1 for i = 1, #lines do @@ -1739,8 +1739,8 @@ end --- --- CAUTION: Modifies the input in-place! --- ---@param lines (table) list of lines ---@returns (string) filetype or 'markdown' if it was unchanged. +---@param lines (table) list of lines +---@returns (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 @@ -1763,7 +1763,7 @@ function M.try_trim_markdown_code_blocks(lines) end local str_utfindex = vim.str_utfindex ---@private +---@private local function make_position_param() local row, col = unpack(api.nvim_win_get_cursor(0)) row = row - 1 @@ -1777,8 +1777,8 @@ end --- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position. --- ---@returns `TextDocumentPositionParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams +---@returns `TextDocumentPositionParams` object +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams function M.make_position_params() return { textDocument = M.make_text_document_params(); @@ -1791,7 +1791,7 @@ end --- `textDocument/codeAction`, `textDocument/colorPresentation`, --- `textDocument/rangeFormatting`. --- ---@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---`current_position`, end = `current_position` } } function M.make_range_params() local position = make_position_param() @@ -1804,11 +1804,11 @@ end --- Using the given range in the current buffer, creates an object that --- is similar to |vim.lsp.util.make_range_params()|. --- ---@param start_pos ({number, number}, optional) mark-indexed position. +---@param start_pos ({number, number}, optional) mark-indexed position. ---Defaults to the start of the last visual selection. ---@param end_pos ({number, number}, optional) mark-indexed position. +---@param end_pos ({number, number}, optional) mark-indexed position. ---Defaults to the end of the last visual selection. ---@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---`start_position`, end = `end_position` } } function M.make_given_range_params(start_pos, end_pos) validate { @@ -1844,23 +1844,23 @@ end --- Creates a `TextDocumentIdentifier` object for the current buffer. --- ---@returns `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier +---@returns `TextDocumentIdentifier` +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params() return { uri = vim.uri_from_bufnr(0) } end --- Create the workspace params ---@param added ---@param removed +---@param added +---@param removed function M.make_workspace_params(added, removed) return { event = { added = added; removed = removed; } } end --- Returns visual width of tabstop. --- ---@see |softtabstop| ---@param bufnr (optional, number): Buffer handle, defaults to current ---@returns (number) tabstop visual width +---@see |softtabstop| +---@param bufnr (optional, number): Buffer handle, defaults to current +---@returns (number) tabstop visual width function M.get_effective_tabstop(bufnr) validate { bufnr = {bufnr, 'n', true} } local bo = bufnr and vim.bo[bufnr] or vim.bo @@ -1870,9 +1870,9 @@ end --- Creates a `DocumentFormattingParams` object for the current buffer and cursor position. --- ---@param options Table with valid `FormattingOptions` entries ---@returns `DocumentFormattingParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting +---@param options Table with valid `FormattingOptions` entries +---@returns `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} } options = vim.tbl_extend('keep', options or {}, { @@ -1887,10 +1887,10 @@ end --- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. --- ---@param buf buffer id (0 for current) ---@param row 0-indexed line ---@param col 0-indexed byte offset in line ---@returns (number, number) UTF-32 and UTF-16 index of the character in line {row} column {col} in buffer {buf} +---@param buf buffer id (0 for current) +---@param row 0-indexed line +---@param col 0-indexed byte offset in line +---@returns (number, number) UTF-32 and UTF-16 index of the character in line {row} column {col} in buffer {buf} function M.character_offset(bufnr, row, col) local uri = vim.uri_from_bufnr(bufnr) local line = M.get_line(uri, row) @@ -1903,9 +1903,9 @@ 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 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 function M.lookup_section(settings, section) for part in vim.gsplit(section, '.', true) do settings = settings[part] @@ -1920,10 +1920,10 @@ end --- Convert diagnostics grouped by bufnr to a list of items for use in the --- quickfix or location list. --- ---@param diagnostics_by_bufnr table bufnr -> Diagnostic[] ---@param predicate an optional function to filter the diagnostics. --- If present, only diagnostic items matching will be included. ---@return table (A list of items) +---@param diagnostics_by_bufnr table bufnr -> Diagnostic[] +---@param predicate an optional function to filter the diagnostics. +--- If present, only diagnostic items matching will be included. +---@return table (A list of items) function M.diagnostics_to_items(diagnostics_by_bufnr, predicate) local items = {} for bufnr, diagnostics in pairs(diagnostics_by_bufnr or {}) do |