refactor(lua): reformat with stylua 0.14.0 (#19264)

* reformat Lua runtime to make lint CI pass
* reduce max line length to 100
This commit is contained in:
Christian Clason
2022-07-07 18:27:18 +02:00
committed by GitHub
parent 34d41baf8a
commit aa4f9c5341
26 changed files with 563 additions and 182 deletions

View File

@ -1,4 +1,4 @@
column_width = 120
column_width = 100
line_endings = "Unix"
indent_type = "Spaces"
indent_width = 2

View File

@ -2094,8 +2094,7 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params})
Lua module: vim.lsp.sync *lsp-sync*
*vim.lsp.sync.compute_diff()*
compute_diff({prev_lines}, {curr_lines}, {firstline}, {lastline},
{new_lastline}, {offset_encoding}, {line_ending})
compute_diff({___MissingCloseParenHere___})
Returns the range table for the difference between prev and
curr lines

View File

@ -739,7 +739,12 @@ function vim._cs_remote(rcid, server_addr, connect_error, args)
f_tab = true
elseif subcmd == 'silent' then
f_silent = true
elseif subcmd == 'wait' or subcmd == 'wait-silent' or subcmd == 'tab-wait' or subcmd == 'tab-wait-silent' then
elseif
subcmd == 'wait'
or subcmd == 'wait-silent'
or subcmd == 'tab-wait'
or subcmd == 'tab-wait-silent'
then
return { errmsg = 'E5600: Wait commands not yet implemented in nvim' }
elseif subcmd == 'tab-silent' then
f_tab = true
@ -795,7 +800,11 @@ function vim.deprecate(name, alternative, version, plugin, backtrace)
local message = name .. ' is deprecated'
plugin = plugin or 'Nvim'
message = alternative and (message .. ', use ' .. alternative .. ' instead.') or message
message = message .. ' See :h deprecated\nThis function will be removed in ' .. plugin .. ' version ' .. version
message = message
.. ' See :h deprecated\nThis function will be removed in '
.. plugin
.. ' version '
.. version
if vim.notify_once(message, vim.log.levels.WARN) and backtrace ~= false then
vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN)
end

View File

@ -102,9 +102,13 @@ do -- buffer option accessor
if type(k) == 'string' then
_setup()
if win_options[k] then
error(string.format([['%s' is a window option, not a buffer option. See ":help %s"]], k, k))
error(
string.format([['%s' is a window option, not a buffer option. See ":help %s"]], k, k)
)
elseif glb_options[k] then
error(string.format([['%s' is a global option, not a buffer option. See ":help %s"]], k, k))
error(
string.format([['%s' is a global option, not a buffer option. See ":help %s"]], k, k)
)
end
end
@ -132,9 +136,13 @@ do -- window option accessor
if type(k) == 'string' then
_setup()
if buf_options[k] then
error(string.format([['%s' is a buffer option, not a window option. See ":help %s"]], k, k))
error(
string.format([['%s' is a buffer option, not a window option. See ":help %s"]], k, k)
)
elseif glb_options[k] then
error(string.format([['%s' is a global option, not a window option. See ":help %s"]], k, k))
error(
string.format([['%s' is a global option, not a window option. See ":help %s"]], k, k)
)
end
end
@ -252,7 +260,12 @@ local function assert_valid_value(name, value, types)
end
error(
string.format("Invalid option type '%s' for '%s', should be %s", type_of_value, name, table.concat(types, ' or '))
string.format(
"Invalid option type '%s' for '%s', should be %s",
type_of_value,
name,
table.concat(types, ' or ')
)
)
end

View File

@ -68,7 +68,10 @@ local all_namespaces = {}
---@private
local function to_severity(severity)
if type(severity) == 'string' then
return assert(M.severity[string.upper(severity)], string.format('Invalid severity: %s', severity))
return assert(
M.severity[string.upper(severity)],
string.format('Invalid severity: %s', severity)
)
end
return severity
end
@ -277,7 +280,8 @@ local function set_diagnostic_cache(namespace, bufnr, diagnostics)
for _, diagnostic in ipairs(diagnostics) do
assert(diagnostic.lnum, 'Diagnostic line number is required')
assert(diagnostic.col, 'Diagnostic column is required')
diagnostic.severity = diagnostic.severity and to_severity(diagnostic.severity) or M.severity.ERROR
diagnostic.severity = diagnostic.severity and to_severity(diagnostic.severity)
or M.severity.ERROR
diagnostic.end_lnum = diagnostic.end_lnum or diagnostic.lnum
diagnostic.end_col = diagnostic.end_col or diagnostic.col
diagnostic.namespace = namespace
@ -322,13 +326,8 @@ local function save_extmarks(namespace, bufnr)
})
diagnostic_attached_buffers[bufnr] = true
end
diagnostic_cache_extmarks[bufnr][namespace] = vim.api.nvim_buf_get_extmarks(
bufnr,
namespace,
0,
-1,
{ details = true }
)
diagnostic_cache_extmarks[bufnr][namespace] =
vim.api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, { details = true })
end
local registered_autocmds = {}
@ -482,7 +481,8 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace)
bufnr = get_bufnr(bufnr)
local wrap = vim.F.if_nil(opts.wrap, true)
local line_count = vim.api.nvim_buf_line_count(bufnr)
local diagnostics = get_diagnostics(bufnr, vim.tbl_extend('keep', opts, { namespace = namespace }), true)
local diagnostics =
get_diagnostics(bufnr, vim.tbl_extend('keep', opts, { namespace = namespace }), true)
local line_diagnostics = diagnostic_lines(diagnostics)
for i = 0, line_count do
local offset = i * (search_forward and 1 or -1)
@ -971,7 +971,10 @@ M.handlers.virtual_text = {
if opts.virtual_text.format then
diagnostics = reformat_diagnostics(opts.virtual_text.format, diagnostics)
end
if opts.virtual_text.source and (opts.virtual_text.source ~= 'if_many' or count_sources(bufnr) > 1) then
if
opts.virtual_text.source
and (opts.virtual_text.source ~= 'if_many' or count_sources(bufnr) > 1)
then
diagnostics = prefix_source(diagnostics)
end
if opts.virtual_text.severity then
@ -1279,7 +1282,9 @@ function M.open_float(opts, ...)
-- LSP servers can send diagnostics with `end_col` past the length of the line
local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1]
diagnostics = vim.tbl_filter(function(d)
return d.lnum == lnum and math.min(d.col, line_length - 1) <= col and (d.end_col >= col or d.end_lnum > lnum)
return d.lnum == lnum
and math.min(d.col, line_length - 1) <= col
and (d.end_col >= col or d.end_lnum > lnum)
end, diagnostics)
end
@ -1333,9 +1338,10 @@ function M.open_float(opts, ...)
diagnostics = prefix_source(diagnostics)
end
local prefix_opt = if_nil(opts.prefix, (scope == 'cursor' and #diagnostics <= 1) and '' or function(_, i)
return string.format('%d. ', i)
end)
local prefix_opt =
if_nil(opts.prefix, (scope == 'cursor' and #diagnostics <= 1) and '' or function(_, i)
return string.format('%d. ', i)
end)
local prefix, prefix_hl_group
if prefix_opt then

View File

@ -176,7 +176,8 @@ local extension = {
bsdl = 'bsdl',
bst = 'bst',
btm = function(path, bufnr)
return (vim.g.dosbatch_syntax_for_btm and vim.g.dosbatch_syntax_for_btm ~= 0) and 'dosbatch' or 'btm'
return (vim.g.dosbatch_syntax_for_btm and vim.g.dosbatch_syntax_for_btm ~= 0) and 'dosbatch'
or 'btm'
end,
bzl = 'bzl',
bazel = 'bzl',
@ -2169,7 +2170,10 @@ local function sort_by_priority(t)
local sorted = {}
for k, v in pairs(t) do
local ft = type(v) == 'table' and v[1] or v
assert(type(ft) == 'string' or type(ft) == 'function', 'Expected string or function for filetype')
assert(
type(ft) == 'string' or type(ft) == 'function',
'Expected string or function for filetype'
)
local opts = (type(v) == 'table' and type(v[2]) == 'table') and v[2] or {}
if not opts.priority then

View File

@ -71,7 +71,8 @@ function M.asm_syntax(bufnr)
end
end
local visual_basic_content = { 'vb_name', 'begin vb%.form', 'begin vb%.mdiform', 'begin vb%.usercontrol' }
local visual_basic_content =
{ 'vb_name', 'begin vb%.form', 'begin vb%.mdiform', 'begin vb%.usercontrol' }
-- See frm() for Visual Basic form file detection
function M.bas(bufnr)
@ -92,7 +93,11 @@ function M.bas(bufnr)
for _, line in ipairs(getlines(bufnr, 1, 100)) do
if findany(line:lower(), visual_basic_content) then
return 'vb'
elseif line:find(fb_comment) or matchregex(line, fb_preproc) or matchregex(line, fb_keywords) then
elseif
line:find(fb_comment)
or matchregex(line, fb_preproc)
or matchregex(line, fb_keywords)
then
return 'freebasic'
elseif matchregex(line, qb64_preproc) then
return 'qb64'
@ -236,7 +241,13 @@ local function cvs_diff(path, contents)
elseif
-- Locale input files: Formal Definitions of Cultural Conventions
-- Filename must be like en_US, fr_FR@euro or en_US.UTF-8
findany(path, { '%a%a_%a%a$', '%a%a_%a%a[%.@]', '%a%a_%a%ai18n$', '%a%a_%a%aPOSIX$', '%a%a_%a%atranslit_' })
findany(path, {
'%a%a_%a%a$',
'%a%a_%a%a[%.@]',
'%a%a_%a%ai18n$',
'%a%a_%a%aPOSIX$',
'%a%a_%a%atranslit_',
})
then
-- Only look at the first 100 lines
for line_nr = 1, 100 do
@ -327,9 +338,11 @@ local function diff(contents)
contents[1]:find('^%-%-%- ') and contents[2]:find('^%+%+%+ ')
or contents[1]:find('^%* looking for ') and contents[2]:find('^%* comparing to ')
or contents[1]:find('^%*%*%* ') and contents[2]:find('^%-%-%- ')
or contents[1]:find('^=== ') and ((contents[2]:find('^' .. string.rep('=', 66)) and contents[3]:find('^%-%-% ') and contents[4]:find(
'^%+%+%+'
)) or (contents[2]:find('^%-%-%- ') and contents[3]:find('^%+%+%+ ')))
or contents[1]:find('^=== ') and ((contents[2]:find('^' .. string.rep('=', 66)) and contents[3]:find(
'^%-%-% '
) and contents[4]:find('^%+%+%+')) or (contents[2]:find('^%-%-%- ') and contents[3]:find(
'^%+%+%+ '
)))
or findany(contents[1], { '^=== removed', '^=== added', '^=== renamed', '^=== modified' })
then
return 'diff'
@ -523,7 +536,8 @@ function M.idl(bufnr)
end
local pascal_comments = { '^%s*{', '^%s*%(%*', '^%s*//' }
local pascal_keywords = [[\c^\s*\%(program\|unit\|library\|uses\|begin\|procedure\|function\|const\|type\|var\)\>]]
local pascal_keywords =
[[\c^\s*\%(program\|unit\|library\|uses\|begin\|procedure\|function\|const\|type\|var\)\>]]
function M.inc(bufnr)
if vim.g.filetype_inc then
@ -574,9 +588,19 @@ end
-- (refactor of filetype.vim since the patterns are case-insensitive)
function M.log(path)
path = path:lower()
if findany(path, { 'upstream%.log', 'upstream%..*%.log', '.*%.upstream%.log', 'upstream%-.*%.log' }) then
if
findany(
path,
{ 'upstream%.log', 'upstream%..*%.log', '.*%.upstream%.log', 'upstream%-.*%.log' }
)
then
return 'upstreamlog'
elseif findany(path, { 'upstreaminstall%.log', 'upstreaminstall%..*%.log', '.*%.upstreaminstall%.log' }) then
elseif
findany(
path,
{ 'upstreaminstall%.log', 'upstreaminstall%..*%.log', '.*%.upstreaminstall%.log' }
)
then
return 'upstreaminstalllog'
elseif findany(path, { 'usserver%.log', 'usserver%..*%.log', '.*%.usserver%.log' }) then
return 'usserverlog'
@ -616,7 +640,8 @@ function M.m(bufnr)
-- Excluding end(for|function|if|switch|while) common to Murphi
local octave_block_terminators =
[[\<end\%(_try_catch\|classdef\|enumeration\|events\|methods\|parfor\|properties\)\>]]
local objc_preprocessor = [[\c^\s*#\s*\%(import\|include\|define\|if\|ifn\=def\|undef\|line\|error\|pragma\)\>]]
local objc_preprocessor =
[[\c^\s*#\s*\%(import\|include\|define\|if\|ifn\=def\|undef\|line\|error\|pragma\)\>]]
-- Whether we've seen a multiline comment leader
local saw_comment = false
@ -627,7 +652,11 @@ function M.m(bufnr)
-- anything more definitive.
saw_comment = true
end
if line:find('^%s*//') or matchregex(line, [[\c^\s*@import\>]]) or matchregex(line, objc_preprocessor) then
if
line:find('^%s*//')
or matchregex(line, [[\c^\s*@import\>]])
or matchregex(line, objc_preprocessor)
then
return 'objc'
end
if
@ -869,7 +898,10 @@ function M.progress_cweb(bufnr)
if vim.g.filetype_w then
return vim.g.filetype_w
else
if getlines(bufnr, 1):lower():find('^&analyze') or getlines(bufnr, 3):lower():find('^&global%-define') then
if
getlines(bufnr, 1):lower():find('^&analyze')
or getlines(bufnr, 3):lower():find('^&global%-define')
then
return 'progress'
else
return 'cweb'
@ -914,10 +946,13 @@ end
function M.psf(bufnr)
local line = getlines(bufnr, 1):lower()
if
findany(
line,
{ '^%s*distribution%s*$', '^%s*installed_software%s*$', '^%s*root%s*$', '^%s*bundle%s*$', '^%s*product%s*$' }
)
findany(line, {
'^%s*distribution%s*$',
'^%s*installed_software%s*$',
'^%s*root%s*$',
'^%s*bundle%s*$',
'^%s*product%s*$',
})
then
return 'psf'
end
@ -960,7 +995,9 @@ end
function M.reg(bufnr)
local line = getlines(bufnr, 1):lower()
if line:find('^regedit[0-9]*%s*$') or line:find('^windows registry editor version %d*%.%d*%s*$') then
if
line:find('^regedit[0-9]*%s*$') or line:find('^windows registry editor version %d*%.%d*%s*$')
then
return 'registry'
end
end
@ -1033,10 +1070,15 @@ end
function M.sc(bufnr)
for _, line in ipairs(getlines(bufnr, 1, 25)) do
if
findany(
line,
{ '[A-Za-z0-9]*%s:%s[A-Za-z0-9]', 'var%s<', 'classvar%s<', '%^this.*', '|%w*|', '%+%s%w*%s{', '%*ar%s' }
)
findany(line, {
'[A-Za-z0-9]*%s:%s[A-Za-z0-9]',
'var%s<',
'classvar%s<',
'%^this.*',
'|%w*|',
'%+%s%w*%s{',
'%*ar%s',
})
then
return 'supercollider'
end
@ -1062,10 +1104,11 @@ function M.sgml(bufnr)
if lines:find('linuxdoc') then
return 'smgllnx'
elseif lines:find('<!DOCTYPE.*DocBook') then
return 'docbk', function(b)
vim.b[b].docbk_type = 'sgml'
vim.b[b].docbk_ver = 4
end
return 'docbk',
function(b)
vim.b[b].docbk_type = 'sgml'
vim.b[b].docbk_ver = 4
end
else
return 'sgml'
end
@ -1194,7 +1237,8 @@ function M.tex(path, bufnr)
if not l:find('^%s*%%%S') then
-- Check the next thousand lines for a LaTeX or ConTeXt keyword.
for _, line in ipairs(getlines(bufnr, i + 1, i + 1000)) do
local lpat_match, cpat_match = matchregex(line, [[\c^\s*\\\%(]] .. lpat .. [[\)\|^\s*\\\(]] .. cpat .. [[\)]])
local lpat_match, cpat_match =
matchregex(line, [[\c^\s*\\\%(]] .. lpat .. [[\)\|^\s*\\\(]] .. cpat .. [[\)]])
if lpat_match then
return 'tex'
elseif cpat_match then
@ -1489,10 +1533,17 @@ local patterns_text = {
-- Scheme scripts
['exec%s%+%S*scheme'] = { 'scheme', { start_lnum = 1, end_lnum = 2 } },
-- Git output
['^\\(commit\\|tree\\|object\\) \\x\\{40,\\}\\>\\|^tag \\S\\+$'] = { 'git', { vim_regex = true } },
['^\\(commit\\|tree\\|object\\) \\x\\{40,\\}\\>\\|^tag \\S\\+$'] = {
'git',
{ vim_regex = true },
},
function(lines)
-- Gprof (gnu profiler)
if lines[1] == 'Flat profile:' and lines[2] == '' and lines[3]:find('^Each sample counts as .* seconds%.$') then
if
lines[1] == 'Flat profile:'
and lines[2] == ''
and lines[3]:find('^Each sample counts as .* seconds%.$')
then
return 'gprof'
end
end,
@ -1515,7 +1566,12 @@ local function match_from_text(contents, path)
if contents[1]:find('^:$') then
-- Bourne-like shell scripts: sh ksh bash bash2
return M.sh(path, contents)
elseif matchregex('\n' .. table.concat(contents, '\n'), [[\n\s*emulate\s\+\%(-[LR]\s\+\)\=[ckz]\=sh\>]]) then
elseif
matchregex(
'\n' .. table.concat(contents, '\n'),
[[\n\s*emulate\s\+\%(-[LR]\s\+\)\=[ckz]\=sh\>]]
)
then
-- Z shell scripts
return 'zsh'
end
@ -1535,7 +1591,10 @@ local function match_from_text(contents, path)
else
local opts = type(v) == 'table' and v[2] or {}
if opts.start_lnum and opts.end_lnum then
assert(not opts.ignore_case, 'ignore_case=true is ignored when start_lnum is also present, needs refactor')
assert(
not opts.ignore_case,
'ignore_case=true is ignored when start_lnum is also present, needs refactor'
)
for i = opts.start_lnum, opts.end_lnum do
if not contents[i] then
break

View File

@ -61,7 +61,8 @@ end
function M.dir(path)
return function(fs)
return vim.loop.fs_scandir_next(fs)
end, vim.loop.fs_scandir(M.normalize(path))
end,
vim.loop.fs_scandir(M.normalize(path))
end
--- Find files or directories in the given path.

View File

@ -16,7 +16,14 @@ function M.create(higroup, hi_info, default)
for k, v in pairs(hi_info) do
table.insert(options, string.format('%s=%s', k, v))
end
vim.cmd(string.format([[highlight %s %s %s]], default and 'default' or '', higroup, table.concat(options, ' ')))
vim.cmd(
string.format(
[[highlight %s %s %s]],
default and 'default' or '',
higroup,
table.concat(options, ' ')
)
)
end
---@private

View File

@ -80,7 +80,13 @@ for i = 0, 31 do
end
local function escape(str)
return (gsub(gsub(gsub(str, '\\', '\\\\'), '(%c)%f[0-9]', longControlCharEscapes), '%c', shortControlCharEscapes))
return (
gsub(
gsub(gsub(str, '\\', '\\\\'), '(%c)%f[0-9]', longControlCharEscapes),
'%c',
shortControlCharEscapes
)
)
end
local function isIdentifier(str)
@ -181,11 +187,13 @@ local function processRecursive(process, item, path, visited)
for k, v in rawpairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
processedCopy[processedKey] =
processRecursive(process, v, makePath(path, processedKey), visited)
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
local mt =
processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
if type(mt) ~= 'table' then
mt = nil
end

View File

@ -200,7 +200,12 @@ local function validate_encoding(encoding)
encoding = { encoding, 's' },
})
return valid_encodings[encoding:lower()]
or error(string.format("Invalid offset encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'", encoding))
or error(
string.format(
"Invalid offset encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'",
encoding
)
)
end
---@internal
@ -211,13 +216,15 @@ end
---@returns (string) the command
---@returns (list of strings) its arguments
function lsp._cmd_parts(input)
vim.validate({ cmd = {
input,
function()
return vim.tbl_islist(input)
end,
'list',
} })
vim.validate({
cmd = {
input,
function()
return vim.tbl_islist(input)
end,
'list',
},
})
local cmd = input[1]
local cmd_args = {}
@ -274,7 +281,11 @@ local function validate_client_config(config)
get_language_id = { config.get_language_id, 'f', true },
})
assert(
(not config.flags or not config.flags.debounce_text_changes or type(config.flags.debounce_text_changes) == 'number'),
(
not config.flags
or not config.flags.debounce_text_changes
or type(config.flags.debounce_text_changes) == 'number'
),
'flags.debounce_text_changes must be a number with the debounce time in milliseconds'
)
@ -474,7 +485,8 @@ do
local uri = vim.uri_from_bufnr(bufnr)
return function(client)
if
vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') == protocol.TextDocumentSyncKind.None
vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change')
== protocol.TextDocumentSyncKind.None
then
return
end
@ -493,7 +505,8 @@ do
if client.is_stopped() or not vim.api.nvim_buf_is_valid(bufnr) then
return
end
local changes = state.use_incremental_sync and buf_state.pending_changes or { full_changes() }
local changes = state.use_incremental_sync and buf_state.pending_changes
or { full_changes() }
client.notify('textDocument/didChange', {
textDocument = {
uri = uri,
@ -852,7 +865,8 @@ end
--- the client has been initialized.
function lsp.start_client(config)
local cleaned_config = validate_client_config(config)
local cmd, cmd_args, offset_encoding = cleaned_config.cmd, cleaned_config.cmd_args, cleaned_config.offset_encoding
local cmd, cmd_args, offset_encoding =
cleaned_config.cmd, cleaned_config.cmd_args, cleaned_config.offset_encoding
config.flags = config.flags or {}
config.settings = config.settings or {}
@ -921,7 +935,8 @@ function lsp.start_client(config)
---@see |vim.lsp.rpc.client_errors| for possible errors. Use
---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name.
function dispatch.on_error(code, err)
local _ = log.error() and log.error(log_prefix, 'on_error', { code = lsp.client_errors[code], err = err })
local _ = log.error()
and log.error(log_prefix, 'on_error', { code = lsp.client_errors[code], err = err })
err_message(log_prefix, ': Error ', lsp.client_errors[code], ': ', vim.inspect(err))
if config.on_error then
local status, usererr = pcall(config.on_error, code, err)
@ -964,7 +979,8 @@ function lsp.start_client(config)
changetracking.reset(client_id)
if code ~= 0 or (signal ~= 0 and signal ~= 15) then
local msg = string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal)
local msg =
string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal)
vim.schedule(function()
vim.notify(msg, vim.log.levels.WARN)
end)
@ -1082,7 +1098,8 @@ function lsp.start_client(config)
-- These are the cleaned up capabilities we use for dynamically deciding
-- when to send certain events to clients.
client.server_capabilities = assert(result.capabilities, "initialize result doesn't contain capabilities")
client.server_capabilities =
assert(result.capabilities, "initialize result doesn't contain capabilities")
client.server_capabilities = protocol.resolve_capabilities(client.server_capabilities)
-- Deprecation wrapper: this will be removed in 0.8
@ -1128,7 +1145,11 @@ function lsp.start_client(config)
end
end
local _ = log.info()
and log.info(log_prefix, 'server_capabilities', { server_capabilities = client.server_capabilities })
and log.info(
log_prefix,
'server_capabilities',
{ server_capabilities = client.server_capabilities }
)
-- Only assign after initialized.
active_clients[client_id] = client
@ -1168,9 +1189,14 @@ function lsp.start_client(config)
-- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state
changetracking.flush(client, bufnr)
bufnr = resolve_bufnr(bufnr)
local _ = log.debug() and log.debug(log_prefix, 'client.request', client_id, method, params, handler, bufnr)
local _ = log.debug()
and log.debug(log_prefix, 'client.request', client_id, method, params, handler, bufnr)
local success, request_id = rpc.request(method, params, function(err, result)
handler(err, result, { method = method, client_id = client_id, bufnr = bufnr, params = params })
handler(
err,
result,
{ method = method, client_id = client_id, bufnr = bufnr, params = params }
)
end, function(request_id)
client.requests[request_id] = nil
nvim_command('doautocmd <nomodeline> User LspRequest')
@ -1322,15 +1348,17 @@ end
--- Notify all attached clients that a buffer has changed.
local text_document_did_change_handler
do
text_document_did_change_handler = function(_, bufnr, changedtick, firstline, lastline, new_lastline)
-- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached
if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then
return true
text_document_did_change_handler =
function(_, bufnr, changedtick, firstline, lastline, new_lastline)
-- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached
if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then
return true
end
util.buf_versions[bufnr] = changedtick
local compute_change_and_notify =
changetracking.prepare(bufnr, firstline, lastline, new_lastline)
for_each_buffer_client(bufnr, compute_change_and_notify)
end
util.buf_versions[bufnr] = changedtick
local compute_change_and_notify = changetracking.prepare(bufnr, firstline, lastline, new_lastline)
for_each_buffer_client(bufnr, compute_change_and_notify)
end
end
-- Buffer lifecycle handler for textDocument/didSave
@ -1369,7 +1397,8 @@ function lsp.buf_attach_client(bufnr, client_id)
})
bufnr = resolve_bufnr(bufnr)
if not vim.api.nvim_buf_is_loaded(bufnr) then
local _ = log.warn() and log.warn(string.format('buf_attach_client called on unloaded buffer (id: %d): ', bufnr))
local _ = log.warn()
and log.warn(string.format('buf_attach_client called on unloaded buffer (id: %d): ', bufnr))
return false
end
local buffer_client_ids = all_buffer_active_clients[bufnr]
@ -1447,7 +1476,13 @@ function lsp.buf_detach_client(bufnr, client_id)
local client = lsp.get_client_by_id(client_id)
if not client or not client.attached_buffers[bufnr] then
vim.notify(string.format('Buffer (id: %d) is not attached to client (id: %d). Cannot detach.', client_id, bufnr))
vim.notify(
string.format(
'Buffer (id: %d) is not attached to client (id: %d). Cannot detach.',
client_id,
bufnr
)
)
return
end
@ -1548,10 +1583,14 @@ function lsp.get_active_clients(filter)
local clients = {}
local t = filter.bufnr and (all_buffer_active_clients[resolve_bufnr(filter.bufnr)] or {}) or active_clients
local t = filter.bufnr and (all_buffer_active_clients[resolve_bufnr(filter.bufnr)] or {})
or active_clients
for client_id in pairs(t) do
local client = active_clients[client_id]
if (filter.id == nil or client.id == filter.id) and (filter.name == nil or client.name == filter.name) then
if
(filter.id == nil or client.id == filter.id)
and (filter.name == nil or client.name == filter.name)
then
clients[#clients + 1] = client
end
end
@ -1643,7 +1682,9 @@ function lsp.buf_request(bufnr, method, params, handler)
end)
-- if has client but no clients support the given method, notify the user
if not tbl_isempty(all_buffer_active_clients[resolve_bufnr(bufnr)] or {}) and not method_supported then
if
not tbl_isempty(all_buffer_active_clients[resolve_bufnr(bufnr)] or {}) and not method_supported
then
vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR)
vim.api.nvim_command('redraw')
return {}, function() end
@ -1888,12 +1929,17 @@ function lsp.formatexpr(opts)
},
}
params.options = util.make_formatting_params().options
local client_results = vim.lsp.buf_request_sync(0, 'textDocument/rangeFormatting', params, timeout_ms)
local client_results =
vim.lsp.buf_request_sync(0, 'textDocument/rangeFormatting', params, timeout_ms)
-- Apply the text edits from one and only one of the clients.
for client_id, response in pairs(client_results) do
if response.result then
vim.lsp.util.apply_text_edits(response.result, 0, vim.lsp.get_client_by_id(client_id).offset_encoding)
vim.lsp.util.apply_text_edits(
response.result,
0,
vim.lsp.get_client_by_id(client_id).offset_encoding
)
return 0
end
end

View File

@ -255,7 +255,13 @@ S.format = P.any(
S.int,
S.colon,
S.slash,
P.any(P.token('upcase'), P.token('downcase'), P.token('capitalize'), P.token('camelcase'), P.token('pascalcase')),
P.any(
P.token('upcase'),
P.token('downcase'),
P.token('capitalize'),
P.token('camelcase'),
P.token('pascalcase')
),
S.close
),
function(values)
@ -272,7 +278,12 @@ S.format = P.any(
S.open,
S.int,
S.colon,
P.seq(S.question, P.opt(P.take_until({ ':' }, { '\\' })), S.colon, P.opt(P.take_until({ '}' }, { '\\' }))),
P.seq(
S.question,
P.opt(P.take_until({ ':' }, { '\\' })),
S.colon,
P.opt(P.take_until({ '}' }, { '\\' }))
),
S.close
),
function(values)
@ -285,7 +296,14 @@ S.format = P.any(
end
),
P.map(
P.seq(S.dollar, S.open, S.int, S.colon, P.seq(S.plus, P.opt(P.take_until({ '}' }, { '\\' }))), S.close),
P.seq(
S.dollar,
S.open,
S.int,
S.colon,
P.seq(S.plus, P.opt(P.take_until({ '}' }, { '\\' }))),
S.close
),
function(values)
return setmetatable({
type = Node.Type.FORMAT,
@ -296,7 +314,15 @@ S.format = P.any(
end
),
P.map(
P.seq(S.dollar, S.open, S.int, S.colon, S.minus, P.opt(P.take_until({ '}' }, { '\\' })), S.close),
P.seq(
S.dollar,
S.open,
S.int,
S.colon,
S.minus,
P.opt(P.take_until({ '}' }, { '\\' })),
S.close
),
function(values)
return setmetatable({
type = Node.Type.FORMAT,
@ -306,14 +332,17 @@ S.format = P.any(
}, Node)
end
),
P.map(P.seq(S.dollar, S.open, S.int, S.colon, P.opt(P.take_until({ '}' }, { '\\' })), S.close), function(values)
return setmetatable({
type = Node.Type.FORMAT,
capture_index = values[3],
if_text = '',
else_text = values[5] and values[5].esc or '',
}, Node)
end)
P.map(
P.seq(S.dollar, S.open, S.int, S.colon, P.opt(P.take_until({ '}' }, { '\\' })), S.close),
function(values)
return setmetatable({
type = Node.Type.FORMAT,
capture_index = values[3],
if_text = '',
else_text = values[5] and values[5].esc or '',
}, Node)
end
)
)
S.transform = P.map(
@ -359,7 +388,14 @@ S.tabstop = P.any(
S.placeholder = P.any(
P.map(
P.seq(S.dollar, S.open, S.int, S.colon, P.opt(P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' })))), S.close),
P.seq(
S.dollar,
S.open,
S.int,
S.colon,
P.opt(P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' })))),
S.close
),
function(values)
return setmetatable({
type = Node.Type.PLACEHOLDER,
@ -419,7 +455,14 @@ S.variable = P.any(
}, Node)
end),
P.map(
P.seq(S.dollar, S.open, S.var, S.colon, P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' }))), S.close),
P.seq(
S.dollar,
S.open,
S.var,
S.colon,
P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' }))),
S.close
),
function(values)
return setmetatable({
type = Node.Type.VARIABLE,

View File

@ -228,7 +228,8 @@ function M.format(options)
end
local params = util.make_formatting_params(options.formatting_options)
client.request('textDocument/formatting', params, function(...)
local handler = client.handlers['textDocument/formatting'] or vim.lsp.handlers['textDocument/formatting']
local handler = client.handlers['textDocument/formatting']
or vim.lsp.handlers['textDocument/formatting']
handler(...)
do_format(next(clients, idx))
end, bufnr)
@ -284,7 +285,10 @@ end
---@param timeout_ms (number) Request timeout
---@see |vim.lsp.buf.formatting_seq_sync|
function M.formatting_sync(options, timeout_ms)
vim.notify_once('vim.lsp.buf.formatting_sync is deprecated. Use vim.lsp.buf.format instead', vim.log.levels.WARN)
vim.notify_once(
'vim.lsp.buf.formatting_sync is deprecated. Use vim.lsp.buf.format instead',
vim.log.levels.WARN
)
local params = util.make_formatting_params(options)
local bufnr = vim.api.nvim_get_current_buf()
select_client('textDocument/formatting', function(client)
@ -318,7 +322,10 @@ end
---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)
vim.notify_once('vim.lsp.buf.formatting_seq_sync is deprecated. Use vim.lsp.buf.format instead', vim.log.levels.WARN)
vim.notify_once(
'vim.lsp.buf.formatting_seq_sync is deprecated. Use vim.lsp.buf.format instead',
vim.log.levels.WARN
)
local clients = vim.tbl_values(vim.lsp.buf_get_clients())
local bufnr = vim.api.nvim_get_current_buf()
@ -346,7 +353,10 @@ function M.formatting_seq_sync(options, timeout_ms, order)
if result and result.result then
util.apply_text_edits(result.result, bufnr, client.offset_encoding)
elseif err then
vim.notify(string.format('vim.lsp.buf.formatting_seq_sync: (%s) %s', client.name, err), vim.log.levels.WARN)
vim.notify(
string.format('vim.lsp.buf.formatting_seq_sync: (%s) %s', client.name, err),
vim.log.levels.WARN
)
end
end
end
@ -429,7 +439,8 @@ function M.rename(new_name, options)
local function rename(name)
local params = util.make_position_params(win, client.offset_encoding)
params.newName = name
local handler = client.handlers['textDocument/rename'] or vim.lsp.handlers['textDocument/rename']
local handler = client.handlers['textDocument/rename']
or vim.lsp.handlers['textDocument/rename']
client.request('textDocument/rename', params, function(...)
handler(...)
try_use_client(next(clients, idx))
@ -443,7 +454,8 @@ function M.rename(new_name, options)
if next(clients, idx) then
try_use_client(next(clients, idx))
else
local msg = err and ('Error on prepareRename: ' .. (err.message or '')) or 'Nothing to rename'
local msg = err and ('Error on prepareRename: ' .. (err.message or ''))
or 'Nothing to rename'
vim.notify(msg, vim.log.levels.INFO)
end
return
@ -475,7 +487,10 @@ function M.rename(new_name, options)
end)
end, bufnr)
else
assert(client.supports_method('textDocument/rename'), 'Client must support textDocument/rename')
assert(
client.supports_method('textDocument/rename'),
'Client must support textDocument/rename'
)
if new_name then
rename(new_name)
return
@ -587,7 +602,8 @@ end
--- Add the folder at path to the workspace folders. If {path} is
--- not provided, the user will be prompted for a path using |input()|.
function M.add_workspace_folder(workspace_folder)
workspace_folder = workspace_folder or npcall(vfn.input, 'Workspace Folder: ', vfn.expand('%:p:h'), 'dir')
workspace_folder = workspace_folder
or npcall(vfn.input, 'Workspace Folder: ', vfn.expand('%:p:h'), 'dir')
vim.api.nvim_command('redraw')
if not (workspace_folder and #workspace_folder > 0) then
return
@ -623,7 +639,8 @@ end
--- {path} is not provided, the user will be prompted for
--- a path using |input()|.
function M.remove_workspace_folder(workspace_folder)
workspace_folder = workspace_folder or npcall(vfn.input, 'Workspace Folder: ', vfn.expand('%:p:h'))
workspace_folder = workspace_folder
or npcall(vfn.input, 'Workspace Folder: ', vfn.expand('%:p:h'))
vim.api.nvim_command('redraw')
if not (workspace_folder and #workspace_folder > 0) then
return

View File

@ -302,7 +302,9 @@ function M.get(bufnr, client_id, predicate)
end
local namespace = M.get_namespace(client_id)
return diagnostic_vim_to_lsp(vim.tbl_filter(predicate, vim.diagnostic.get(bufnr, { namespace = namespace })))
return diagnostic_vim_to_lsp(
vim.tbl_filter(predicate, vim.diagnostic.get(bufnr, { namespace = namespace }))
)
end
--- Get the diagnostics by line
@ -483,7 +485,12 @@ function M.set_signs(diagnostics, bufnr, client_id, _, opts)
opts.severity = { min = severity_lsp_to_vim(opts.severity_limit) }
end
vim.diagnostic._set_signs(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id), opts)
vim.diagnostic._set_signs(
namespace,
bufnr,
diagnostic_lsp_to_vim(diagnostics, bufnr, client_id),
opts
)
end
--- Set underline for given diagnostics
@ -503,7 +510,12 @@ function M.set_underline(diagnostics, bufnr, client_id, _, opts)
if opts and not opts.severity and opts.severity_limit then
opts.severity = { min = severity_lsp_to_vim(opts.severity_limit) }
end
return vim.diagnostic._set_underline(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id), opts)
return vim.diagnostic._set_underline(
namespace,
bufnr,
diagnostic_lsp_to_vim(diagnostics, bufnr, client_id),
opts
)
end
--- Set virtual text given diagnostics
@ -525,7 +537,12 @@ function M.set_virtual_text(diagnostics, bufnr, client_id, _, opts)
if opts and not opts.severity and opts.severity_limit then
opts.severity = { min = severity_lsp_to_vim(opts.severity_limit) }
end
return vim.diagnostic._set_virtual_text(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id), opts)
return vim.diagnostic._set_virtual_text(
namespace,
bufnr,
diagnostic_lsp_to_vim(diagnostics, bufnr, client_id),
opts
)
end
--- Default function to get text chunks to display using |nvim_buf_set_extmark()|.

View File

@ -125,7 +125,8 @@ M['workspace/applyEdit'] = function(_, workspace_edit, ctx)
if workspace_edit.label then
print('Workspace edit', workspace_edit.label)
end
local status, result = pcall(util.apply_workspace_edit, workspace_edit.edit, client.offset_encoding)
local status, result =
pcall(util.apply_workspace_edit, workspace_edit.edit, client.offset_encoding)
return {
applied = status,
failureReason = result,
@ -137,7 +138,11 @@ M['workspace/configuration'] = function(_, result, ctx)
local client_id = ctx.client_id
local client = vim.lsp.get_client_by_id(client_id)
if not client then
err_message('LSP[', client_id, '] client has shut down after sending a workspace/configuration request')
err_message(
'LSP[',
client_id,
'] client has shut down after sending a workspace/configuration request'
)
return
end
if not result.items then
@ -239,10 +244,14 @@ local function response_to_list(map_result, entity, title_fn)
end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
M['textDocument/documentSymbol'] = response_to_list(util.symbols_to_items, 'document symbols', function(ctx)
local fname = vim.fn.fnamemodify(vim.uri_to_fname(ctx.params.textDocument.uri), ':.')
return string.format('Symbols in %s', fname)
end)
M['textDocument/documentSymbol'] = response_to_list(
util.symbols_to_items,
'document symbols',
function(ctx)
local fname = vim.fn.fnamemodify(vim.uri_to_fname(ctx.params.textDocument.uri), ':.')
return string.format('Symbols in %s', fname)
end
)
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol
M['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols', function(ctx)
@ -391,7 +400,8 @@ function M.signature_help(_, result, ctx, config)
return
end
local client = vim.lsp.get_client_by_id(ctx.client_id)
local triggers = vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters')
local triggers =
vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters')
local ft = api.nvim_buf_get_option(ctx.bufnr, 'filetype')
local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers)
lines = util.trim_empty_lines(lines)

View File

@ -11,7 +11,12 @@ function M.check()
report_info(string.format('LSP log level : %s', log_level_string))
if current_log_level < log.levels.WARN then
report_warn(string.format('Log level %s will cause degraded performance and high disk usage', log_level_string))
report_warn(
string.format(
'Log level %s will cause degraded performance and high disk usage',
log_level_string
)
)
end
local log_path = vim.lsp.get_log_path()

View File

@ -59,7 +59,11 @@ do
local log_info = vim.loop.fs_stat(logfilename)
if log_info and log_info.size > 1e9 then
local warn_msg = string.format('LSP client log is large (%d MB): %s', log_info.size / (1000 * 1000), logfilename)
local warn_msg = string.format(
'LSP client log is large (%d MB): %s',
log_info.size / (1000 * 1000),
logfilename
)
vim.notify(warn_msg)
end
@ -129,7 +133,8 @@ vim.tbl_add_reverse_lookup(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))
current_log_level =
assert(log.levels[level:upper()], string.format('Invalid log level: %q', level))
else
assert(type(level) == 'number', 'level must be a number or string')
assert(log.levels[level], string.format('Invalid log level: %d', level))

View File

@ -880,7 +880,8 @@ function protocol._resolve_capabilities_compat(server_capabilities)
general_properties.document_symbol = server_capabilities.documentSymbolProvider or false
general_properties.workspace_symbol = server_capabilities.workspaceSymbolProvider or false
general_properties.document_formatting = server_capabilities.documentFormattingProvider or false
general_properties.document_range_formatting = server_capabilities.documentRangeFormattingProvider or false
general_properties.document_range_formatting = server_capabilities.documentRangeFormattingProvider
or false
general_properties.call_hierarchy = server_capabilities.callHierarchyProvider or false
general_properties.execute_command = server_capabilities.executeCommandProvider ~= nil
@ -897,7 +898,8 @@ function protocol._resolve_capabilities_compat(server_capabilities)
general_properties.code_lens_resolve = false
elseif type(server_capabilities.codeLensProvider) == 'table' then
general_properties.code_lens = true
general_properties.code_lens_resolve = server_capabilities.codeLensProvider.resolveProvider or false
general_properties.code_lens_resolve = server_capabilities.codeLensProvider.resolveProvider
or false
else
error('The server sent invalid codeLensProvider')
end
@ -974,7 +976,8 @@ function protocol._resolve_capabilities_compat(server_capabilities)
signature_help_properties = {
signature_help = true,
-- The characters that trigger signature help automatically.
signature_help_trigger_characters = server_capabilities.signatureHelpProvider.triggerCharacters or {},
signature_help_trigger_characters = server_capabilities.signatureHelpProvider.triggerCharacters
or {},
}
else
error('The server sent invalid signatureHelpProvider')

View File

@ -115,7 +115,8 @@ local function request_parser_loop()
local body_length = #body_chunks[1]
-- Keep waiting for data until we have enough.
while body_length < content_length do
local chunk = coroutine.yield() or error('Expected more data for the body. The server may have died.') -- TODO hmm.
local chunk = coroutine.yield()
or error('Expected more data for the body. The server may have died.') -- TODO hmm.
table.insert(body_chunks, chunk)
body_length = body_length + #chunk
end
@ -129,10 +130,16 @@ local function request_parser_loop()
local body = table.concat(body_chunks)
-- Yield our data.
buffer = rest
.. (coroutine.yield(headers, body) or error('Expected more data for the body. The server may have died.')) -- TODO hmm.
.. (
coroutine.yield(headers, body)
or error('Expected more data for the body. The server may have died.')
) -- TODO hmm.
else
-- Get more data since we don't have enough.
buffer = buffer .. (coroutine.yield() or error('Expected more data for the header. The server may have died.')) -- TODO hmm.
buffer = buffer
.. (
coroutine.yield() or error('Expected more data for the header. The server may have died.')
) -- TODO hmm.
end
end
end
@ -262,7 +269,8 @@ end
--- - {handle} A handle for low-level interaction with the LSP server process
--- |vim.loop|.
local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
local _ = log.info() and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params })
local _ = log.info()
and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params })
validate({
cmd = { cmd, 's' },
cmd_args = { cmd_args, 't' },
@ -336,7 +344,8 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
if handle == nil then
local msg = string.format('Spawning language server with cmd: `%s` failed', cmd)
if string.match(pid, 'ENOENT') then
msg = msg .. '. The language server is either not installed, missing from PATH, or not executable.'
msg = msg
.. '. The language server is either not installed, missing from PATH, or not executable.'
else
msg = msg .. string.format(' with error message: %s', pid)
end
@ -476,7 +485,10 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
decoded.params
)
local _ = log.debug()
and log.debug('server_request: callback result', { status = status, result = result, err = err })
and log.debug(
'server_request: callback result',
{ status = status, result = result, err = err }
)
if status then
if not (result or err) then
-- TODO this can be a problem if `null` is sent for result. needs vim.NIL
@ -488,7 +500,10 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
)
end
if err then
assert(type(err) == 'table', 'err must be a table. Use rpc_response_error to help format errors.')
assert(
type(err) == 'table',
'err must be a table. Use rpc_response_error to help format errors.'
)
local code_name = assert(
protocol.ErrorCodes[err.code],
'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.'
@ -549,14 +564,25 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
__tostring = format_rpc_error,
})
end
try_call(client_errors.SERVER_RESULT_CALLBACK_ERROR, callback, decoded.error, decoded.result)
try_call(
client_errors.SERVER_RESULT_CALLBACK_ERROR,
callback,
decoded.error,
decoded.result
)
else
on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded)
local _ = log.error() and log.error('No callback found for server response id ' .. result_id)
local _ = log.error()
and log.error('No callback found for server response id ' .. result_id)
end
elseif type(decoded.method) == 'string' then
-- Notification
try_call(client_errors.NOTIFICATION_HANDLER_ERROR, dispatchers.notification, decoded.method, decoded.params)
try_call(
client_errors.NOTIFICATION_HANDLER_ERROR,
dispatchers.notification,
decoded.method,
decoded.params
)
else
-- Invalid server message
on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)

View File

@ -130,7 +130,14 @@ end
---@param new_lastline integer new_lastline from on_lines, adjusted to 1-index
---@param offset_encoding string utf-8|utf-16|utf-32|nil (fallback to utf-8)
---@returns table<int, int> line_idx, byte_idx, and char_idx of first change position
local function compute_start_range(prev_lines, curr_lines, firstline, lastline, new_lastline, offset_encoding)
local function compute_start_range(
prev_lines,
curr_lines,
firstline,
lastline,
new_lastline,
offset_encoding
)
local char_idx
local byte_idx
-- If firstline == lastline, no existing text is changed. All edit operations
@ -249,13 +256,19 @@ local function compute_end_range(
local max_length
if start_line_idx == prev_line_idx then
-- Search until beginning of difference
max_length = min(prev_line_length - start_range.byte_idx, curr_line_length - start_range.byte_idx) + 1
max_length = min(
prev_line_length - start_range.byte_idx,
curr_line_length - start_range.byte_idx
) + 1
else
max_length = min(prev_line_length, curr_line_length) + 1
end
for idx = 0, max_length do
byte_offset = idx
if str_byte(prev_line, prev_line_length - byte_offset) ~= str_byte(curr_line, curr_line_length - byte_offset) then
if
str_byte(prev_line, prev_line_length - byte_offset)
~= str_byte(curr_line, curr_line_length - byte_offset)
then
break
end
end
@ -268,8 +281,10 @@ local function compute_end_range(
if prev_end_byte_idx == 0 then
prev_end_byte_idx = 1
end
local prev_byte_idx, prev_char_idx = align_end_position(prev_line, prev_end_byte_idx, offset_encoding)
local prev_end_range = { line_idx = prev_line_idx, byte_idx = prev_byte_idx, char_idx = prev_char_idx }
local prev_byte_idx, prev_char_idx =
align_end_position(prev_line, prev_end_byte_idx, offset_encoding)
local prev_end_range =
{ line_idx = prev_line_idx, byte_idx = prev_byte_idx, char_idx = prev_char_idx }
local curr_end_range
-- Deletion event, new_range cannot be before start
@ -281,8 +296,10 @@ local function compute_end_range(
if curr_end_byte_idx == 0 then
curr_end_byte_idx = 1
end
local curr_byte_idx, curr_char_idx = align_end_position(curr_line, curr_end_byte_idx, offset_encoding)
curr_end_range = { line_idx = curr_line_idx, byte_idx = curr_byte_idx, char_idx = curr_char_idx }
local curr_byte_idx, curr_char_idx =
align_end_position(curr_line, curr_end_byte_idx, offset_encoding)
curr_end_range =
{ line_idx = curr_line_idx, byte_idx = curr_byte_idx, char_idx = curr_char_idx }
end
return prev_end_range, curr_end_range
@ -341,7 +358,10 @@ local function compute_range_length(lines, start_range, end_range, offset_encodi
local start_line = lines[start_range.line_idx]
local range_length
if start_line and #start_line > 0 then
range_length = compute_line_length(start_line, offset_encoding) - start_range.char_idx + 1 + line_ending_length
range_length = compute_line_length(start_line, offset_encoding)
- start_range.char_idx
+ 1
+ line_ending_length
else
-- Length of newline character
range_length = line_ending_length
@ -373,7 +393,15 @@ end
---@param new_lastline number line to begin search in new_lines for last difference
---@param offset_encoding string encoding requested by language server
---@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent
function M.compute_diff(prev_lines, curr_lines, firstline, lastline, new_lastline, offset_encoding, line_ending)
function M.compute_diff(
prev_lines,
curr_lines,
firstline,
lastline,
new_lastline,
offset_encoding,
line_ending
)
-- Find the start of changes between the previous and current buffer. Common between both.
-- Sent to the server as the start of the changed range.
-- Used to grab the changed text from the latest buffer.
@ -403,7 +431,8 @@ function M.compute_diff(prev_lines, curr_lines, firstline, lastline, new_lastlin
local text = extract_text(curr_lines, start_range, curr_end_range, line_ending)
-- Compute the range of the replaced text. Deprecated but still required for certain language servers
local range_length = compute_range_length(prev_lines, start_range, prev_end_range, offset_encoding, line_ending)
local range_length =
compute_range_length(prev_lines, start_range, prev_end_range, offset_encoding, line_ending)
-- convert to 0 based indexing
local result = {

View File

@ -44,7 +44,8 @@ end
---@private
local function query_workspace_symbols(pattern)
local results_by_client, err = lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000)
local results_by_client, err =
lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000)
if err then
return {}
end

View File

@ -44,12 +44,22 @@ local function get_border_size(opts)
shadow = { 1, 1 },
}
if border_size[border] == nil then
error(string.format('invalid floating preview border: %s. :help vim.api.nvim_open_win()', vim.inspect(border)))
error(
string.format(
'invalid floating preview border: %s. :help vim.api.nvim_open_win()',
vim.inspect(border)
)
)
end
height, width = unpack(border_size[border])
else
if 8 % #border ~= 0 then
error(string.format('invalid floating preview border: %s. :help vim.api.nvim_open_win()', vim.inspect(border)))
error(
string.format(
'invalid floating preview border: %s. :help vim.api.nvim_open_win()',
vim.inspect(border)
)
)
end
---@private
local function border_width(id)
@ -61,7 +71,12 @@ local function get_border_size(opts)
-- border specified as a list of border characters
return vim.fn.strdisplaywidth(border[id])
end
error(string.format('invalid floating preview border: %s. :help vim.api.nvim_open_win()', vim.inspect(border)))
error(
string.format(
'invalid floating preview border: %s. :help vim.api.nvim_open_win()',
vim.inspect(border)
)
)
end
---@private
local function border_height(id)
@ -73,7 +88,12 @@ local function get_border_size(opts)
-- border specified as a list of border characters
return #border[id] > 0 and 1 or 0
end
error(string.format('invalid floating preview border: %s. :help vim.api.nvim_open_win()', vim.inspect(border)))
error(
string.format(
'invalid floating preview border: %s. :help vim.api.nvim_open_win()',
vim.inspect(border)
)
)
end
height = height + border_height(2) -- top
height = height + border_height(6) -- bottom
@ -531,7 +551,10 @@ function M.apply_text_document_edit(text_document_edit, index, offset_encoding)
local text_document = text_document_edit.textDocument
local bufnr = vim.uri_to_bufnr(text_document.uri)
if offset_encoding == nil then
vim.notify_once('apply_text_document_edit must be called with valid offset encoding', vim.log.levels.WARN)
vim.notify_once(
'apply_text_document_edit must be called with valid offset encoding',
vim.log.levels.WARN
)
end
-- For lists of text document edits,
@ -765,7 +788,10 @@ end
--see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
function M.apply_workspace_edit(workspace_edit, offset_encoding)
if offset_encoding == nil then
vim.notify_once('apply_workspace_edit must be called with valid offset encoding', vim.log.levels.WARN)
vim.notify_once(
'apply_workspace_edit must be called with valid offset encoding',
vim.log.levels.WARN
)
end
if workspace_edit.documentChanges then
for idx, change in ipairs(workspace_edit.documentChanges) do
@ -1022,7 +1048,10 @@ function M.jump_to_location(location, offset_encoding, reuse_win)
return
end
if offset_encoding == nil then
vim.notify_once('jump_to_location must be called with valid offset encoding', vim.log.levels.WARN)
vim.notify_once(
'jump_to_location must be called with valid offset encoding',
vim.log.levels.WARN
)
end
local bufnr = vim.uri_to_bufnr(uri)
-- Save position in jumplist
@ -1226,14 +1255,21 @@ function M.stylize_markdown(bufnr, contents, opts)
-- strip any empty lines or separators prior to this separator in actual markdown
if line:match('^---+$') then
while
markdown_lines[#stripped] and (stripped[#stripped]:match('^%s*$') or stripped[#stripped]:match('^---+$'))
markdown_lines[#stripped]
and (stripped[#stripped]:match('^%s*$') or stripped[#stripped]:match('^---+$'))
do
markdown_lines[#stripped] = false
table.remove(stripped, #stripped)
end
end
-- add the line if its not an empty line following a separator
if not (line:match('^%s*$') and markdown_lines[#stripped] and stripped[#stripped]:match('^---+$')) then
if
not (
line:match('^%s*$')
and markdown_lines[#stripped]
and stripped[#stripped]:match('^---+$')
)
then
table.insert(stripped, line)
markdown_lines[#stripped] = true
end
@ -1265,7 +1301,11 @@ function M.stylize_markdown(bufnr, contents, opts)
local function apply_syntax_to_region(ft, start, finish)
if ft == '' then
vim.cmd(
string.format('syntax region markdownCode start=+\\%%%dl+ end=+\\%%%dl+ keepend extend', start, finish + 1)
string.format(
'syntax region markdownCode start=+\\%%%dl+ end=+\\%%%dl+ keepend extend',
start,
finish + 1
)
)
return
end
@ -1283,7 +1323,13 @@ function M.stylize_markdown(bufnr, contents, opts)
langs[lang] = true
end
vim.cmd(
string.format('syntax region %s start=+\\%%%dl+ end=+\\%%%dl+ contains=%s keepend', name, start, finish + 1, lang)
string.format(
'syntax region %s start=+\\%%%dl+ end=+\\%%%dl+ contains=%s keepend',
name,
start,
finish + 1,
lang
)
)
end
@ -1587,15 +1633,21 @@ do --[[ References ]]
offset_encoding = { offset_encoding, 'string', false },
})
for _, reference in ipairs(references) do
local start_line, start_char = reference['range']['start']['line'], reference['range']['start']['character']
local end_line, end_char = reference['range']['end']['line'], reference['range']['end']['character']
local start_line, start_char =
reference['range']['start']['line'], reference['range']['start']['character']
local end_line, end_char =
reference['range']['end']['line'], reference['range']['end']['character']
local start_idx = get_line_byte_from_position(
bufnr,
{ line = start_line, character = start_char },
offset_encoding
)
local end_idx = get_line_byte_from_position(bufnr, { line = start_line, character = end_char }, offset_encoding)
local end_idx = get_line_byte_from_position(
bufnr,
{ line = start_line, character = end_char },
offset_encoding
)
local document_highlight_kind = {
[protocol.DocumentHighlightKind.Text] = 'LspReferenceText',
@ -1630,7 +1682,10 @@ end)
---@returns (table) list of items
function M.locations_to_items(locations, offset_encoding)
if offset_encoding == nil then
vim.notify_once('locations_to_items must be called with valid offset encoding', vim.log.levels.WARN)
vim.notify_once(
'locations_to_items must be called with valid offset encoding',
vim.log.levels.WARN
)
end
local items = {}
@ -1857,7 +1912,10 @@ function M._get_offset_encoding(bufnr)
for _, client in pairs(vim.lsp.buf_get_clients(bufnr)) do
if client.offset_encoding == nil then
vim.notify_once(
string.format('Client (id: %s) offset_encoding is nil. Do not unset offset_encoding.', client.id),
string.format(
'Client (id: %s) offset_encoding is nil. Do not unset offset_encoding.',
client.id
),
vim.log.levels.ERROR
)
end
@ -1994,7 +2052,10 @@ end
function M.character_offset(buf, row, col, offset_encoding)
local line = get_line(buf, row)
if offset_encoding == nil then
vim.notify_once('character_offset must be called with valid offset encoding', vim.log.levels.WARN)
vim.notify_once(
'character_offset must be called with valid offset encoding',
vim.log.levels.WARN
)
end
-- If the col is past the EOL, use the line length.
if col > #line then

View File

@ -254,7 +254,11 @@ local function tbl_extend(behavior, deep_extend, ...)
end
if select('#', ...) < 2 then
error('wrong number of arguments (given ' .. tostring(1 + select('#', ...)) .. ', expected at least 3)')
error(
'wrong number of arguments (given '
.. tostring(1 + select('#', ...))
.. ', expected at least 3)'
)
end
local ret = {}
@ -650,7 +654,8 @@ do
-- Check user-provided validation function
local valid, optional_message = types(val)
if not valid then
local error_message = string.format('%s: expected %s, got %s', param_name, (spec[3] or '?'), tostring(val))
local error_message =
string.format('%s: expected %s, got %s', param_name, (spec[3] or '?'), tostring(val))
if optional_message ~= nil then
error_message = error_message .. string.format('. Info: %s', optional_message)
end
@ -672,7 +677,13 @@ do
end
end
if not success then
return false, string.format('%s: expected %s, got %s', param_name, table.concat(types, '|'), type(val))
return false,
string.format(
'%s: expected %s, got %s',
param_name,
table.concat(types, '|'),
type(val)
)
end
else
return false, string.format('invalid type name: %s', tostring(types))

View File

@ -26,7 +26,9 @@ function M.check()
report_error(string.format('Impossible to load parser for %s: %s', parsername, ret))
elseif ret then
local lang = ts.language.inspect_language(parsername)
report_ok(string.format('Loaded parser for %s: ABI version %d', parsername, lang._abi_version))
report_ok(
string.format('Loaded parser for %s: ABI version %d', parsername, lang._abi_version)
)
else
report_error(string.format('Unable to load parser for %s', parsername))
end

View File

@ -280,7 +280,8 @@ local function on_line_impl(self, buf, line)
end
if state.iter == nil or state.next_row < line then
state.iter = highlighter_query:query():iter_captures(root_node, self.bufnr, line, root_end_row + 1)
state.iter =
highlighter_query:query():iter_captures(root_node, self.bufnr, line, root_end_row + 1)
end
while line >= state.next_row do

View File

@ -32,10 +32,8 @@ function LanguageTree.new(source, lang, opts)
_regions = {},
_trees = {},
_opts = opts,
_injection_query = injections[lang] and query.parse_query(lang, injections[lang]) or query.get_query(
lang,
'injections'
),
_injection_query = injections[lang] and query.parse_query(lang, injections[lang])
or query.get_query(lang, 'injections'),
_valid = false,
_parser = vim._create_ts_parser(lang),
_callbacks = {