fix(lsp): lint warnings, default offset_encoding #24046

- fix lint / analysis warnings
- locations_to_items(): get default offset_encoding from active client
- character_offset(): get default offset_encoding from active client
This commit is contained in:
Raphael 2023-07-01 18:42:37 +08:00 committed by GitHub
parent 11844dde81
commit ba8f19ebb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 130 additions and 113 deletions

View File

@ -1078,9 +1078,12 @@ add_workspace_folder({workspace_folder})
Add the folder at path to the workspace folders. If {path} is not Add the folder at path to the workspace folders. If {path} is not
provided, the user will be prompted for a path using |input()|. provided, the user will be prompted for a path using |input()|.
clear_references() *vim.lsp.buf.clear_references()* clear_references({bufnr}) *vim.lsp.buf.clear_references()*
Removes document highlights from current buffer. Removes document highlights from current buffer.
Parameters: ~
• {bufnr} integer|nil
code_action({options}) *vim.lsp.buf.code_action()* code_action({options}) *vim.lsp.buf.code_action()*
Selects a code action available at the current cursor position. Selects a code action available at the current cursor position.
@ -1587,12 +1590,12 @@ character_offset({buf}, {row}, {col}, {offset_encoding})
• {buf} (integer) buffer number (0 for current) • {buf} (integer) buffer number (0 for current)
• {row} 0-indexed line • {row} 0-indexed line
• {col} 0-indexed byte offset in line • {col} 0-indexed byte offset in line
• {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to • {offset_encoding} (string) utf-8|utf-16|utf-32 defaults to
`offset_encoding` of first client of `buf` `offset_encoding` of first client of `buf`
Return: ~ Return: ~
(integer, integer) `offset_encoding` index of the character in line (integer) `offset_encoding` index of the character in line {row}
{row} column {col} in buffer {buf} column {col} in buffer {buf}
*vim.lsp.util.convert_input_to_markdown_lines()* *vim.lsp.util.convert_input_to_markdown_lines()*
convert_input_to_markdown_lines({input}, {contents}) convert_input_to_markdown_lines({input}, {contents})
@ -1607,7 +1610,7 @@ convert_input_to_markdown_lines({input}, {contents})
lines. Defaults to {}. lines. Defaults to {}.
Return: ~ Return: ~
{contents}, extended with lines of converted markdown. (table) {contents} extended with lines of converted markdown.
See also: ~ See also: ~
• https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
@ -1617,14 +1620,15 @@ convert_signature_help_to_markdown_lines({signature_help}, {ft}, {triggers})
Converts `textDocument/SignatureHelp` response to markdown lines. Converts `textDocument/SignatureHelp` response to markdown lines.
Parameters: ~ Parameters: ~
• {signature_help} Response of `textDocument/SignatureHelp` • {signature_help} (table) Response of `textDocument/SignatureHelp`
• {ft} optional filetype that will be use as the `lang` for • {ft} (string|nil) filetype that will be use as the `lang`
the label markdown code block for the label markdown code block
• {triggers} optional list of trigger characters from the lsp • {triggers} (table|nil) list of trigger characters from the lsp
server. used to better determine parameter offsets server. used to better determine parameter offsets
Return: ~ Return: ~
(list) of lines of converted markdown. (table|nil) table list of lines of converted markdown.
(table|nil) table of active hl
See also: ~ See also: ~
• https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp
@ -1660,7 +1664,7 @@ jump_to_location({location}, {offset_encoding}, {reuse_win})
Parameters: ~ Parameters: ~
• {location} (table) (`Location`|`LocationLink`) • {location} (table) (`Location`|`LocationLink`)
• {offset_encoding} "utf-8" | "utf-16" | "utf-32" • {offset_encoding} (string|nil) utf-8|utf-16|utf-32
• {reuse_win} (boolean|nil) Jump to existing window if buffer is • {reuse_win} (boolean|nil) Jump to existing window if buffer is
already open. already open.
@ -1678,7 +1682,8 @@ locations_to_items({locations}, {offset_encoding})
Parameters: ~ Parameters: ~
• {locations} (table) list of `Location`s or `LocationLink`s • {locations} (table) list of `Location`s or `LocationLink`s
• {offset_encoding} (string) offset_encoding for locations • {offset_encoding} (string) offset_encoding for locations
utf-8|utf-16|utf-32 utf-8|utf-16|utf-32 default to first client of
buffer
Return: ~ Return: ~
(table) list of items (table) list of items
@ -1687,11 +1692,11 @@ lookup_section({settings}, {section}) *vim.lsp.util.lookup_section()*
Helper function to return nested values in language server settings Helper function to return nested values in language server settings
Parameters: ~ Parameters: ~
• {settings} a table of language server settings • {settings} (table) language server settings
• {section} a string indicating the field of the settings table • {section} string indicating the field of the settings table
Return: ~ Return: ~
(table or string) The value of settings accessed via section table|string The value of settings accessed via section
*vim.lsp.util.make_floating_popup_options()* *vim.lsp.util.make_floating_popup_options()*
make_floating_popup_options({width}, {height}, {opts}) make_floating_popup_options({width}, {height}, {opts})
@ -1701,7 +1706,7 @@ make_floating_popup_options({width}, {height}, {opts})
Parameters: ~ Parameters: ~
• {width} (integer) window width (in character cells) • {width} (integer) window width (in character cells)
• {height} (integer) window height (in character cells) • {height} (integer) window height (in character cells)
• {opts} (table, optional) • {opts} (table) optional
• offset_x (integer) offset to add to `col` • offset_x (integer) offset to add to `col`
• offset_y (integer) offset to add to `row` • offset_y (integer) offset to add to `row`
• border (string or table) override `border` • border (string or table) override `border`
@ -1742,8 +1747,8 @@ make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding})
`offset_encoding` of first client of `bufnr` `offset_encoding` of first client of `bufnr`
Return: ~ Return: ~
{ textDocument = { uri = `current_file_uri` }, range = { start = (table) { textDocument = { uri = `current_file_uri` }, range = { start
`start_position`, end = `end_position` } } = `start_position`, end = `end_position` } }
*vim.lsp.util.make_position_params()* *vim.lsp.util.make_position_params()*
make_position_params({window}, {offset_encoding}) make_position_params({window}, {offset_encoding})
@ -1758,7 +1763,7 @@ make_position_params({window}, {offset_encoding})
`window` `window`
Return: ~ Return: ~
`TextDocumentPositionParams` object (table) `TextDocumentPositionParams` object
See also: ~ See also: ~
• https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams
@ -1778,8 +1783,8 @@ make_range_params({window}, {offset_encoding})
`window` `window`
Return: ~ Return: ~
{ textDocument = { uri = `current_file_uri` }, range = { start = (table) { textDocument = { uri = `current_file_uri` }, range = { start
`current_position`, end = `current_position` } } = `current_position`, end = `current_position` } }
*vim.lsp.util.make_text_document_params()* *vim.lsp.util.make_text_document_params()*
make_text_document_params({bufnr}) make_text_document_params({bufnr})
@ -1789,7 +1794,7 @@ make_text_document_params({bufnr})
• {bufnr} (integer|nil) Buffer handle, defaults to current • {bufnr} (integer|nil) Buffer handle, defaults to current
Return: ~ Return: ~
`TextDocumentIdentifier` (table) `TextDocumentIdentifier`
See also: ~ See also: ~
• https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier
@ -1799,8 +1804,8 @@ make_workspace_params({added}, {removed})
Create the workspace params Create the workspace params
Parameters: ~ Parameters: ~
• {added} • {added} (table)
• {removed} • {removed} (table)
*vim.lsp.util.open_floating_preview()* *vim.lsp.util.open_floating_preview()*
open_floating_preview({contents}, {syntax}, {opts}) open_floating_preview({contents}, {syntax}, {opts})
@ -1832,8 +1837,8 @@ open_floating_preview({contents}, {syntax}, {opts})
window with the same {focus_id} window with the same {focus_id}
Return: ~ Return: ~
bufnr,winnr buffer and window number of the newly created floating (integer) bufnr of newly created float window
preview window (integer) winid of newly created float window preview window
parse_snippet({input}) *vim.lsp.util.parse_snippet()* parse_snippet({input}) *vim.lsp.util.parse_snippet()*
Parses snippets in a completion entry. Parses snippets in a completion entry.
@ -1853,10 +1858,11 @@ preview_location({location}, {opts}) *vim.lsp.util.preview_location()*
definition) definition)
Parameters: ~ Parameters: ~
• {location} a single `Location` or `LocationLink` • {location} (table) a single `Location` or `LocationLink`
Return: ~ Return: ~
(bufnr,winnr) buffer and window number of floating window or nil (integer|nil) buffer id of float window
(integer|nil) window id of float window
rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()* rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()*
Rename old_fname to new_fname Rename old_fname to new_fname
@ -1873,7 +1879,7 @@ set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()*
• {lines} (table) Original list of strings • {lines} (table) Original list of strings
• {A} (table) Start position; a 2-tuple of {line,col} numbers • {A} (table) Start position; a 2-tuple of {line,col} numbers
• {B} (table) End position; a 2-tuple of {line,col} numbers • {B} (table) End position; a 2-tuple of {line,col} numbers
• {new_lines} A list of strings to replace the original • {new_lines} (table) list of strings to replace the original
Return: ~ Return: ~
(table) The modified {lines} object (table) The modified {lines} object
@ -1884,7 +1890,7 @@ show_document({location}, {offset_encoding}, {opts})
Parameters: ~ Parameters: ~
• {location} (table) (`Location`|`LocationLink`) • {location} (table) (`Location`|`LocationLink`)
• {offset_encoding} "utf-8" | "utf-16" | "utf-32" • {offset_encoding} (string|nil) utf-8|utf-16|utf-32
• {opts} (table|nil) options • {opts} (table|nil) options
• reuse_win (boolean) Jump to existing window if • reuse_win (boolean) Jump to existing window if
buffer is already open. buffer is already open.
@ -1908,7 +1914,7 @@ stylize_markdown({bufnr}, {contents}, {opts})
Parameters: ~ Parameters: ~
• {contents} (table) of lines to show in window • {contents} (table) of lines to show in window
• {opts} dictionary with optional fields • {opts} (table) with optional fields
• height of floating window • height of floating window
• width of floating window • width of floating window
• wrap_at character to wrap at for computing height • wrap_at character to wrap at for computing height
@ -1919,13 +1925,13 @@ stylize_markdown({bufnr}, {contents}, {opts})
• separator insert separator after code block • separator insert separator after code block
Return: ~ Return: ~
width,height size of float (table) stripped content
symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()* symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()*
Converts symbols to quickfix list items. Converts symbols to quickfix list items.
Parameters: ~ Parameters: ~
• {symbols} DocumentSymbol[] or SymbolInformation[] • {symbols} (table) DocumentSymbol[] or SymbolInformation[]
*vim.lsp.util.text_document_completion_list_to_complete_items()* *vim.lsp.util.text_document_completion_list_to_complete_items()*
text_document_completion_list_to_complete_items({result}, {prefix}) text_document_completion_list_to_complete_items({result}, {prefix})
@ -1933,16 +1939,16 @@ text_document_completion_list_to_complete_items({result}, {prefix})
vim-compatible |complete-items|. vim-compatible |complete-items|.
Parameters: ~ Parameters: ~
• {result} The result of a `textDocument/completion` call, e.g. from • {result} (table) The result of a `textDocument/completion` call, e.g.
|vim.lsp.buf.completion()|, which may be one of from |vim.lsp.buf.completion()|, which may be one of
`CompletionItem[]`, `CompletionList` or `null` `CompletionItem[]`, `CompletionList` or `null`
• {prefix} (string) the prefix to filter the completion items • {prefix} (string) the prefix to filter the completion items
Return: ~ Return: ~
{ matches = complete-items table, incomplete = bool } (table) { matches = complete-items table, incomplete = bool }
See also: ~ See also: ~
|complete-items| • complete-items
trim_empty_lines({lines}) *vim.lsp.util.trim_empty_lines()* trim_empty_lines({lines}) *vim.lsp.util.trim_empty_lines()*
Removes empty lines from the beginning and end. Removes empty lines from the beginning and end.
@ -1980,7 +1986,7 @@ get_level() *vim.lsp.log.get_level()*
Gets the current log level. Gets the current log level.
Return: ~ Return: ~
(string) current log level (integer) current log level
set_format_func({handle}) *vim.lsp.log.set_format_func()* set_format_func({handle}) *vim.lsp.log.set_format_func()*
Sets formatting function used to format logs Sets formatting function used to format logs
@ -2117,6 +2123,6 @@ resolve_capabilities({server_capabilities})
server server
Return: ~ Return: ~
(table) Normalized table of capabilities (table|nil) Normalized table of capabilities
vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:

View File

@ -581,9 +581,9 @@ function M.document_highlight()
end end
--- Removes document highlights from current buffer. --- Removes document highlights from current buffer.
--- --- @param bufnr integer|nil
function M.clear_references() function M.clear_references(bufnr)
util.buf_clear_references() util.buf_clear_references(bufnr or 0)
end end
---@private ---@private

View File

@ -33,11 +33,9 @@ local function execute_lens(lens, bufnr, client_id)
local client = vim.lsp.get_client_by_id(client_id) local client = vim.lsp.get_client_by_id(client_id)
assert(client, 'Client is required to execute lens, client_id=' .. client_id) assert(client, 'Client is required to execute lens, client_id=' .. client_id)
client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) client._exec_cmd(lens.command, { bufnr = bufnr }, function(...)
local result = vim.lsp.handlers['workspace/executeCommand'](...) vim.lsp.handlers['workspace/executeCommand'](...)
M.refresh() M.refresh()
return result
end) end)
end end

View File

@ -154,7 +154,7 @@ function log.set_level(level)
end end
--- Gets the current log level. --- Gets the current log level.
---@return string current log level ---@return integer current log level
function log.get_level() function log.get_level()
return current_log_level return current_log_level
end end

View File

@ -880,7 +880,7 @@ end
--- Creates a normalized object describing LSP server capabilities. --- Creates a normalized object describing LSP server capabilities.
---@param server_capabilities table Table of capabilities supported by the server ---@param server_capabilities table Table of capabilities supported by the server
---@return table Normalized table of capabilities ---@return table|nil Normalized table of capabilities
function protocol.resolve_capabilities(server_capabilities) function protocol.resolve_capabilities(server_capabilities)
local TextDocumentSyncKind = protocol.TextDocumentSyncKind local TextDocumentSyncKind = protocol.TextDocumentSyncKind
local textDocumentSync = server_capabilities.textDocumentSync local textDocumentSync = server_capabilities.textDocumentSync
@ -898,7 +898,8 @@ function protocol.resolve_capabilities(server_capabilities)
elseif type(textDocumentSync) == 'number' then elseif type(textDocumentSync) == 'number' then
-- Backwards compatibility -- Backwards compatibility
if not TextDocumentSyncKind[textDocumentSync] then if not TextDocumentSyncKind[textDocumentSync] then
return nil, 'Invalid server TextDocumentSyncKind for textDocumentSync' vim.notify('Invalid server TextDocumentSyncKind for textDocumentSync', vim.log.levels.ERROR)
return nil
end end
server_capabilities.textDocumentSync = { server_capabilities.textDocumentSync = {
openClose = true, openClose = true,
@ -910,7 +911,11 @@ function protocol.resolve_capabilities(server_capabilities)
}, },
} }
elseif type(textDocumentSync) ~= 'table' then elseif type(textDocumentSync) ~= 'table' then
return nil, string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)) vim.notify(
string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)),
vim.log.levels.ERROR
)
return nil
end end
return server_capabilities return server_capabilities
end end

View File

@ -36,7 +36,7 @@ end
local function parse_headers(header) local function parse_headers(header)
assert(type(header) == 'string', 'header must be a string') assert(type(header) == 'string', 'header must be a string')
local headers = {} local headers = {}
for line in vim.gsplit(header, '\r\n', true) do for line in vim.gsplit(header, '\r\n', { plain = true }) do
if line == '' then if line == '' then
break break
end end

View File

@ -25,9 +25,9 @@ local default_border = {
---@private ---@private
--- Check the border given by opts or the default border for the additional --- Check the border given by opts or the default border for the additional
--- size it adds to a float. --- size it adds to a float.
---@param opts (table, optional) options for the floating window ---@param opts table optional options for the floating window
--- - border (string or table) the border --- - border (string or table) the border
---@returns (table) size of border in the form of { height = height, width = width } ---@return table size of border in the form of { height = height, width = width }
local function get_border_size(opts) local function get_border_size(opts)
local border = opts and opts.border or default_border local border = opts and opts.border or default_border
local height = 0 local height = 0
@ -106,7 +106,7 @@ end
---@private ---@private
local function split_lines(value) local function split_lines(value)
value = string.gsub(value, '\r\n?', '\n') value = string.gsub(value, '\r\n?', '\n')
return split(value, '\n', true) return split(value, '\n', { plain = true })
end end
---@private ---@private
@ -122,7 +122,7 @@ end
--- Convenience wrapper around vim.str_utfindex --- Convenience wrapper around vim.str_utfindex
---@param line string line to be indexed ---@param line string line to be indexed
---@param index integer|nil byte index (utf-8), or `nil` for length ---@param index integer|nil byte index (utf-8), or `nil` for length
---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ---@param encoding string|nil utf-8|utf-16|utf-32|nil defaults to utf-16
---@return integer `encoding` index of `index` in `line` ---@return integer `encoding` index of `index` in `line`
function M._str_utfindex_enc(line, index, encoding) function M._str_utfindex_enc(line, index, encoding)
if not encoding then if not encoding then
@ -150,7 +150,7 @@ end
---Alternative to vim.str_byteindex that takes an encoding. ---Alternative to vim.str_byteindex that takes an encoding.
---@param line string line to be indexed ---@param line string line to be indexed
---@param index integer UTF index ---@param index integer UTF index
---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ---@param encoding string utf-8|utf-16|utf-32| defaults to utf-16
---@return integer byte (utf-8) index of `encoding` index `index` in `line` ---@return integer byte (utf-8) index of `encoding` index `index` in `line`
function M._str_byteindex_enc(line, index, encoding) function M._str_byteindex_enc(line, index, encoding)
if not encoding then if not encoding then
@ -180,8 +180,8 @@ local _str_byteindex_enc = M._str_byteindex_enc
---@param lines (table) Original list of strings ---@param lines (table) Original list of strings
---@param A (table) Start position; a 2-tuple of {line,col} numbers ---@param A (table) Start position; a 2-tuple of {line,col} numbers
---@param B (table) End position; a 2-tuple of {line,col} numbers ---@param B (table) End position; a 2-tuple of {line,col} numbers
---@param new_lines A list of strings to replace the original ---@param new_lines (table) list of strings to replace the original
---@returns (table) The modified {lines} object ---@return table The modified {lines} object
function M.set_lines(lines, A, B, new_lines) function M.set_lines(lines, A, B, new_lines)
-- 0-indexing to 1-indexing -- 0-indexing to 1-indexing
local i_0 = A[1] + 1 local i_0 = A[1] + 1
@ -241,7 +241,7 @@ end
--- ---
---@param bufnr integer bufnr to get the lines from ---@param bufnr integer bufnr to get the lines from
---@param rows integer[] zero-indexed line numbers ---@param rows integer[] zero-indexed line numbers
---@return table<integer, string> a table mapping rows to lines ---@return table<integer, string>|string a table mapping rows to lines
local function get_lines(bufnr, rows) local function get_lines(bufnr, rows)
rows = type(rows) == 'table' and rows or { rows } rows = type(rows) == 'table' and rows or { rows }
@ -331,8 +331,9 @@ end
---@private ---@private
--- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position --- 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 --- Returns a zero-indexed column, since set_lines() does the conversion to
---@param offset_encoding string utf-8|utf-16|utf-32 ---@param offset_encoding string|nil utf-8|utf-16|utf-32
--- 1-indexed --- 1-indexed
---@return integer
local function get_line_byte_from_position(bufnr, position, offset_encoding) local function get_line_byte_from_position(bufnr, position, offset_encoding)
-- LSP's line and characters are 0-indexed -- LSP's line and characters are 0-indexed
-- Vim's line and columns are 1-indexed -- Vim's line and columns are 1-indexed
@ -598,8 +599,8 @@ end
--- Can be used to extract the completion items from a --- Can be used to extract the completion items from a
--- `textDocument/completion` request, which may return one of --- `textDocument/completion` request, which may return one of
--- `CompletionItem[]`, `CompletionList` or null. --- `CompletionItem[]`, `CompletionList` or null.
---@param result (table) The result of a `textDocument/completion` request ---@param result table The result of a `textDocument/completion` request
---@returns (table) List of completion items ---@return table List of completion items
---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion
function M.extract_completion_items(result) function M.extract_completion_items(result)
if type(result) == 'table' and result.items then if type(result) == 'table' and result.items then
@ -658,7 +659,7 @@ end
--- Parses snippets in a completion entry. --- Parses snippets in a completion entry.
--- ---
---@param input string unparsed snippet ---@param input string unparsed snippet
---@returns string parsed snippet ---@return string parsed snippet
function M.parse_snippet(input) function M.parse_snippet(input)
local ok, parsed = pcall(function() local ok, parsed = pcall(function()
return tostring(snippet.parse(input)) return tostring(snippet.parse(input))
@ -718,7 +719,7 @@ end
--- specification. --- specification.
--- ---
---@param completion_item_kind (`vim.lsp.protocol.completionItemKind`) ---@param completion_item_kind (`vim.lsp.protocol.completionItemKind`)
---@returns (`vim.lsp.protocol.completionItemKind`) ---@return (`vim.lsp.protocol.completionItemKind`)
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
function M._get_completion_item_kind_name(completion_item_kind) function M._get_completion_item_kind_name(completion_item_kind)
return protocol.CompletionItemKind[completion_item_kind] or 'Unknown' return protocol.CompletionItemKind[completion_item_kind] or 'Unknown'
@ -727,12 +728,12 @@ end
--- Turns the result of a `textDocument/completion` request into vim-compatible --- Turns the result of a `textDocument/completion` request into vim-compatible
--- |complete-items|. --- |complete-items|.
--- ---
---@param result The result of a `textDocument/completion` call, e.g. from ---@param result table The result of a `textDocument/completion` call, e.g. from
---|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, ---|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`,
--- `CompletionList` or `null` --- `CompletionList` or `null`
---@param prefix (string) the prefix to filter the completion items ---@param prefix (string) the prefix to filter the completion items
---@returns { matches = complete-items table, incomplete = bool } ---@return table { matches = complete-items table, incomplete = bool }
---@see |complete-items| ---@see complete-items
function M.text_document_completion_list_to_complete_items(result, prefix) function M.text_document_completion_list_to_complete_items(result, prefix)
local items = M.extract_completion_items(result) local items = M.extract_completion_items(result)
if vim.tbl_isempty(items) then if vim.tbl_isempty(items) then
@ -937,7 +938,7 @@ end
--- ---
---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`)
---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}.
---@returns {contents}, extended with lines of converted markdown. ---@return table {contents} extended with lines of converted markdown.
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
function M.convert_input_to_markdown_lines(input, contents) function M.convert_input_to_markdown_lines(input, contents)
contents = contents or {} contents = contents or {}
@ -985,10 +986,11 @@ end
--- Converts `textDocument/SignatureHelp` response to markdown lines. --- Converts `textDocument/SignatureHelp` response to markdown lines.
--- ---
---@param signature_help Response of `textDocument/SignatureHelp` ---@param signature_help table Response of `textDocument/SignatureHelp`
---@param ft optional filetype that will be use as the `lang` for the label markdown code block ---@param ft string|nil 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 ---@param triggers table|nil list of trigger characters from the lsp server. used to better determine parameter offsets
---@returns list of lines of converted markdown. ---@return table|nil table list of lines of converted markdown.
---@return table|nil table of active hl
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp ---@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) function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers)
if not signature_help.signatures then if not signature_help.signatures then
@ -1015,7 +1017,7 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers
-- wrap inside a code block so stylize_markdown can render it properly -- wrap inside a code block so stylize_markdown can render it properly
label = ('```%s\n%s\n```'):format(ft, label) label = ('```%s\n%s\n```'):format(ft, label)
end end
list_extend(contents, split(label, '\n', true)) list_extend(contents, split(label, '\n', { plain = true }))
if signature.documentation then if signature.documentation then
M.convert_input_to_markdown_lines(signature.documentation, contents) M.convert_input_to_markdown_lines(signature.documentation, contents)
end end
@ -1087,16 +1089,16 @@ end
--- Creates a table with sensible default options for a floating window. The --- Creates a table with sensible default options for a floating window. The
--- table can be passed to |nvim_open_win()|. --- table can be passed to |nvim_open_win()|.
--- ---
---@param width (integer) window width (in character cells) ---@param width integer window width (in character cells)
---@param height (integer) window height (in character cells) ---@param height integer window height (in character cells)
---@param opts (table, optional) ---@param opts table optional
--- - offset_x (integer) offset to add to `col` --- - offset_x (integer) offset to add to `col`
--- - offset_y (integer) offset to add to `row` --- - offset_y (integer) offset to add to `row`
--- - border (string or table) override `border` --- - border (string or table) override `border`
--- - focusable (string or table) override `focusable` --- - focusable (string or table) override `focusable`
--- - zindex (string or table) override `zindex`, defaults to 50 --- - zindex (string or table) override `zindex`, defaults to 50
--- - relative ("mouse"|"cursor") defaults to "cursor" --- - relative ("mouse"|"cursor") defaults to "cursor"
---@returns (table) Options ---@return table Options
function M.make_floating_popup_options(width, height, opts) function M.make_floating_popup_options(width, height, opts)
validate({ validate({
opts = { opts, 't', true }, opts = { opts, 't', true },
@ -1160,7 +1162,7 @@ end
--- Shows document and optionally jumps to the location. --- Shows document and optionally jumps to the location.
--- ---
---@param location table (`Location`|`LocationLink`) ---@param location table (`Location`|`LocationLink`)
---@param offset_encoding "utf-8" | "utf-16" | "utf-32" ---@param offset_encoding string|nil utf-8|utf-16|utf-32
---@param opts table|nil options ---@param opts table|nil options
--- - reuse_win (boolean) Jump to existing window if buffer is already open. --- - reuse_win (boolean) Jump to existing window if buffer is already open.
--- - focus (boolean) Whether to focus/jump to location if possible. Defaults to true. --- - focus (boolean) Whether to focus/jump to location if possible. Defaults to true.
@ -1217,7 +1219,7 @@ end
--- Jumps to a location. --- Jumps to a location.
--- ---
---@param location table (`Location`|`LocationLink`) ---@param location table (`Location`|`LocationLink`)
---@param offset_encoding "utf-8" | "utf-16" | "utf-32" ---@param offset_encoding string|nil utf-8|utf-16|utf-32
---@param reuse_win boolean|nil Jump to existing window if buffer is already open. ---@param reuse_win boolean|nil Jump to existing window if buffer is already open.
---@return boolean `true` if the jump succeeded ---@return boolean `true` if the jump succeeded
function M.jump_to_location(location, offset_encoding, reuse_win) function M.jump_to_location(location, offset_encoding, reuse_win)
@ -1237,8 +1239,9 @@ end
--- - for Location, range is shown (e.g., function definition) --- - for Location, range is shown (e.g., function definition)
--- - for LocationLink, targetRange is shown (e.g., body of function definition) --- - for LocationLink, targetRange is shown (e.g., body of function definition)
--- ---
---@param location a single `Location` or `LocationLink` ---@param location table a single `Location` or `LocationLink`
---@returns (bufnr,winnr) buffer and window number of floating window or nil ---@return integer|nil buffer id of float window
---@return integer|nil window id of float window
function M.preview_location(location, opts) function M.preview_location(location, opts)
-- location may be LocationLink or Location (more useful for the former) -- location may be LocationLink or Location (more useful for the former)
local uri = location.targetUri or location.uri local uri = location.targetUri or location.uri
@ -1275,10 +1278,10 @@ end
--- Trims empty lines from input and pad top and bottom with empty lines --- Trims empty lines from input and pad top and bottom with empty lines
--- ---
---@param contents table of lines to trim and pad ---@param contents table of lines to trim and pad
---@param opts dictionary with optional fields ---@param opts table with optional fields
--- - pad_top number of lines to pad contents at top (default 0) --- - pad_top number of lines to pad contents at top (default 0)
--- - pad_bottom number of lines to pad contents at bottom (default 0) --- - pad_bottom number of lines to pad contents at bottom (default 0)
---@return contents table of trimmed and padded lines ---@return table table of trimmed and padded lines
function M._trim(contents, opts) function M._trim(contents, opts)
validate({ validate({
contents = { contents, 't' }, contents = { contents, 't' },
@ -1301,7 +1304,7 @@ end
--- Generates a table mapping markdown code block lang to vim syntax, --- Generates a table mapping markdown code block lang to vim syntax,
--- based on g:markdown_fenced_languages --- based on g:markdown_fenced_languages
---@return a table of lang -> syntax mappings ---@return table table of lang -> syntax mappings
---@private ---@private
local function get_markdown_fences() local function get_markdown_fences()
local fences = {} local fences = {}
@ -1324,7 +1327,7 @@ end
--- If you want to open a popup with fancy markdown, use `open_floating_preview` instead --- If you want to open a popup with fancy markdown, use `open_floating_preview` instead
--- ---
---@param contents table of lines to show in window ---@param contents table of lines to show in window
---@param opts dictionary with optional fields ---@param opts table with optional fields
--- - height of floating window --- - height of floating window
--- - width of floating window --- - width of floating window
--- - wrap_at character to wrap at for computing height --- - wrap_at character to wrap at for computing height
@ -1333,7 +1336,7 @@ end
--- - pad_top number of lines to pad contents at top --- - pad_top number of lines to pad contents at top
--- - pad_bottom number of lines to pad contents at bottom --- - pad_bottom number of lines to pad contents at bottom
--- - separator insert separator after code block --- - separator insert separator after code block
---@returns width,height size of float ---@return table stripped content
function M.stylize_markdown(bufnr, contents, opts) function M.stylize_markdown(bufnr, contents, opts)
validate({ validate({
contents = { contents, 't' }, contents = { contents, 't' },
@ -1480,10 +1483,10 @@ function M.stylize_markdown(bufnr, contents, opts)
if not langs[lang] then if not langs[lang] then
-- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set -- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set
pcall(api.nvim_buf_del_var, bufnr, 'current_syntax') pcall(api.nvim_buf_del_var, bufnr, 'current_syntax')
-- TODO(ashkan): better validation before this. if #api.nvim_get_runtime_file(('syntax/%s.vim'):format(ft), true) == 0 then
if not pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) then
return return
end end
vim.cmd(string.format('syntax include %s syntax/%s.vim', lang, ft))
langs[lang] = true langs[lang] = true
end end
vim.cmd( vim.cmd(
@ -1542,7 +1545,7 @@ end
---@param events table list of events ---@param events table list of events
---@param winnr integer window id of preview window ---@param winnr integer window id of preview window
---@param bufnrs table list of buffers where the preview window will remain visible ---@param bufnrs table list of buffers where the preview window will remain visible
---@see |autocmd-events| ---@see autocmd-events
local function close_preview_autocmd(events, winnr, bufnrs) local function close_preview_autocmd(events, winnr, bufnrs)
local augroup = api.nvim_create_augroup('preview_window_' .. winnr, { local augroup = api.nvim_create_augroup('preview_window_' .. winnr, {
clear = true, clear = true,
@ -1572,13 +1575,14 @@ end
--- Computes size of float needed to show contents (with optional wrapping) --- Computes size of float needed to show contents (with optional wrapping)
--- ---
---@param contents table of lines to show in window ---@param contents table of lines to show in window
---@param opts dictionary with optional fields ---@param opts table with optional fields
--- - height of floating window --- - height of floating window
--- - width of floating window --- - width of floating window
--- - wrap_at character to wrap at for computing height --- - wrap_at character to wrap at for computing height
--- - max_width maximal width of floating window --- - max_width maximal width of floating window
--- - max_height maximal height of floating window --- - max_height maximal height of floating window
---@returns width,height size of float ---@return integer width size of float
---@return integer height size of float
function M._make_floating_popup_size(contents, opts) function M._make_floating_popup_size(contents, opts)
validate({ validate({
contents = { contents, 't' }, contents = { contents, 't' },
@ -1662,7 +1666,8 @@ end
--- - focus: (boolean, default true) If `true`, and if {focusable} --- - focus: (boolean, default true) If `true`, and if {focusable}
--- is also `true`, focus an existing floating window with the same --- is also `true`, focus an existing floating window with the same
--- {focus_id} --- {focus_id}
---@returns bufnr,winnr buffer and window number of the newly created floating ---@return integer bufnr of newly created float window
---@return integer winid of newly created float window
---preview window ---preview window
function M.open_floating_preview(contents, syntax, opts) function M.open_floating_preview(contents, syntax, opts)
validate({ validate({
@ -1766,7 +1771,7 @@ do --[[ References ]]
--- ---
---@param bufnr integer Buffer id ---@param bufnr integer Buffer id
function M.buf_clear_references(bufnr) function M.buf_clear_references(bufnr)
validate({ bufnr = { bufnr, 'n', true } }) validate({ bufnr = { bufnr, { 'n', 'nil' }, true } })
api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1)
end end
@ -1828,13 +1833,15 @@ end)
--- ---
---@param locations table list of `Location`s or `LocationLink`s ---@param locations table list of `Location`s or `LocationLink`s
---@param offset_encoding string offset_encoding for locations utf-8|utf-16|utf-32 ---@param offset_encoding string offset_encoding for locations utf-8|utf-16|utf-32
---@returns (table) list of items --- default to first client of buffer
---@return table list of items
function M.locations_to_items(locations, offset_encoding) function M.locations_to_items(locations, offset_encoding)
if offset_encoding == nil then if offset_encoding == nil then
vim.notify_once( vim.notify_once(
'locations_to_items must be called with valid offset encoding', 'locations_to_items must be called with valid offset encoding',
vim.log.levels.WARN vim.log.levels.WARN
) )
offset_encoding = vim.lsp.get_active_clients({ bufnr = 0 })[1].offset_encoding
end end
local items = {} local items = {}
@ -1896,7 +1903,7 @@ end
--- Converts symbols to quickfix list items. --- Converts symbols to quickfix list items.
--- ---
---@param symbols DocumentSymbol[] or SymbolInformation[] ---@param symbols table DocumentSymbol[] or SymbolInformation[]
function M.symbols_to_items(symbols, bufnr) function M.symbols_to_items(symbols, bufnr)
---@private ---@private
local function _symbols_to_items(_symbols, _items, _bufnr) local function _symbols_to_items(_symbols, _items, _bufnr)
@ -1936,8 +1943,8 @@ function M.symbols_to_items(symbols, bufnr)
end end
--- Removes empty lines from the beginning and end. --- Removes empty lines from the beginning and end.
---@param lines (table) list of lines to trim ---@param lines table list of lines to trim
---@returns (table) trimmed list of lines ---@return table trimmed list of lines
function M.trim_empty_lines(lines) function M.trim_empty_lines(lines)
local start = 1 local start = 1
for i = 1, #lines do for i = 1, #lines do
@ -1961,8 +1968,8 @@ end
--- ---
--- CAUTION: Modifies the input in-place! --- CAUTION: Modifies the input in-place!
--- ---
---@param lines (table) list of lines ---@param lines table list of lines
---@returns (string) filetype or "markdown" if it was unchanged. ---@return string filetype or "markdown" if it was unchanged.
function M.try_trim_markdown_code_blocks(lines) function M.try_trim_markdown_code_blocks(lines)
local language_id = lines[1]:match('^```(.*)') local language_id = lines[1]:match('^```(.*)')
if language_id then if language_id then
@ -2007,7 +2014,7 @@ end
--- ---
---@param window integer|nil: window handle or 0 for current, defaults to current ---@param window integer|nil: window handle or 0 for current, defaults to current
---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window`
---@returns `TextDocumentPositionParams` object ---@return table `TextDocumentPositionParams` object
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams
function M.make_position_params(window, offset_encoding) function M.make_position_params(window, offset_encoding)
window = window or 0 window = window or 0
@ -2021,7 +2028,7 @@ end
--- Utility function for getting the encoding of the first LSP client on the given buffer. --- Utility function for getting the encoding of the first LSP client on the given buffer.
---@param bufnr (integer) buffer handle or 0 for current, defaults to current ---@param bufnr (integer) buffer handle or 0 for current, defaults to current
---@returns (string) encoding first client if there is one, nil otherwise ---@return string encoding first client if there is one, nil otherwise
function M._get_offset_encoding(bufnr) function M._get_offset_encoding(bufnr)
validate({ validate({
bufnr = { bufnr, 'n', true }, bufnr = { bufnr, 'n', true },
@ -2060,7 +2067,7 @@ end
--- ---
---@param window integer|nil: window handle or 0 for current, defaults to current ---@param window integer|nil: window handle or 0 for current, defaults to current
---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window` ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window`
---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---@return table { textDocument = { uri = `current_file_uri` }, range = { start =
---`current_position`, end = `current_position` } } ---`current_position`, end = `current_position` } }
function M.make_range_params(window, offset_encoding) function M.make_range_params(window, offset_encoding)
local buf = api.nvim_win_get_buf(window or 0) local buf = api.nvim_win_get_buf(window or 0)
@ -2081,7 +2088,7 @@ end
--- Defaults to the end of the last visual selection. --- Defaults to the end of the last visual selection.
---@param bufnr integer|nil buffer handle or 0 for current, defaults to current ---@param bufnr integer|nil buffer handle or 0 for current, defaults to current
---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr`
---@returns { textDocument = { uri = `current_file_uri` }, range = { start = ---@return table { textDocument = { uri = `current_file_uri` }, range = { start =
---`start_position`, end = `end_position` } } ---`start_position`, end = `end_position` } }
function M.make_given_range_params(start_pos, end_pos, bufnr, offset_encoding) function M.make_given_range_params(start_pos, end_pos, bufnr, offset_encoding)
validate({ validate({
@ -2121,15 +2128,15 @@ end
--- Creates a `TextDocumentIdentifier` object for the current buffer. --- Creates a `TextDocumentIdentifier` object for the current buffer.
--- ---
---@param bufnr integer|nil: Buffer handle, defaults to current ---@param bufnr integer|nil: Buffer handle, defaults to current
---@returns `TextDocumentIdentifier` ---@return table `TextDocumentIdentifier`
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier
function M.make_text_document_params(bufnr) function M.make_text_document_params(bufnr)
return { uri = vim.uri_from_bufnr(bufnr or 0) } return { uri = vim.uri_from_bufnr(bufnr or 0) }
end end
--- Create the workspace params --- Create the workspace params
---@param added ---@param added table
---@param removed ---@param removed table
function M.make_workspace_params(added, removed) function M.make_workspace_params(added, removed)
return { event = { added = added, removed = removed } } return { event = { added = added, removed = removed } }
end end
@ -2137,7 +2144,7 @@ end
--- ---
---@see 'shiftwidth' ---@see 'shiftwidth'
---@param bufnr (integer|nil): Buffer handle, defaults to current ---@param bufnr (integer|nil): Buffer handle, defaults to current
---@returns (integer) indentation size ---@return (integer) indentation size
function M.get_effective_tabstop(bufnr) function M.get_effective_tabstop(bufnr)
validate({ bufnr = { bufnr, 'n', true } }) validate({ bufnr = { bufnr, 'n', true } })
local bo = bufnr and vim.bo[bufnr] or vim.bo local bo = bufnr and vim.bo[bufnr] or vim.bo
@ -2148,7 +2155,7 @@ end
--- Creates a `DocumentFormattingParams` object for the current buffer and cursor position. --- Creates a `DocumentFormattingParams` object for the current buffer and cursor position.
--- ---
---@param options table|nil with valid `FormattingOptions` entries ---@param options table|nil with valid `FormattingOptions` entries
---@returns `DocumentFormattingParams` object ---@return `DocumentFormattingParams` object
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
function M.make_formatting_params(options) function M.make_formatting_params(options)
validate({ options = { options, 't', true } }) validate({ options = { options, 't', true } })
@ -2167,8 +2174,8 @@ end
---@param buf integer buffer number (0 for current) ---@param buf integer buffer number (0 for current)
---@param row 0-indexed line ---@param row 0-indexed line
---@param col 0-indexed byte offset in line ---@param col 0-indexed byte offset in line
---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of `buf` ---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf`
---@returns (integer, integer) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} ---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf}
function M.character_offset(buf, row, col, offset_encoding) function M.character_offset(buf, row, col, offset_encoding)
local line = get_line(buf, row) local line = get_line(buf, row)
if offset_encoding == nil then if offset_encoding == nil then
@ -2176,6 +2183,7 @@ function M.character_offset(buf, row, col, offset_encoding)
'character_offset must be called with valid offset encoding', 'character_offset must be called with valid offset encoding',
vim.log.levels.WARN vim.log.levels.WARN
) )
offset_encoding = vim.lsp.get_active_clients({ bufnr = buf })[1].offset_encoding
end end
-- If the col is past the EOL, use the line length. -- If the col is past the EOL, use the line length.
if col > #line then if col > #line then
@ -2186,11 +2194,11 @@ end
--- Helper function to return nested values in language server settings --- Helper function to return nested values in language server settings
--- ---
---@param settings a table of language server settings ---@param settings table language server settings
---@param section a string indicating the field of the settings table ---@param section string indicating the field of the settings table
---@returns (table or string) The value of settings accessed via section ---@return table|string The value of settings accessed via section
function M.lookup_section(settings, section) function M.lookup_section(settings, section)
for part in vim.gsplit(section, '.', true) do for part in vim.gsplit(section, '.', { plain = true }) do
settings = settings[part] settings = settings[part]
if settings == nil then if settings == nil then
return vim.NIL return vim.NIL