refactor: address emmylua diagnostics

This commit is contained in:
2026-04-20 22:11:18 +02:00
parent 516b9ea749
commit c7dd083083
29 changed files with 542 additions and 532 deletions
+3 -2
View File
@@ -3,9 +3,10 @@ kind = "Space"
width = 4 width = 4
[layout] [layout]
max_line_width = 80 max_line_width = 79
max_blank_lines = 1 max_blank_lines = 1
call_args_expand = "Always"
[output] [output]
trailing_comma = "Multiline" trailing_table_separator = "Multiline"
quote_style = "Double" quote_style = "Double"
+1 -1
View File
@@ -7,7 +7,7 @@ return {
"bash", "bash",
"zsh", "zsh",
}, },
on_attach = function(client, bufnr) on_attach = function(_, bufnr)
vim.keymap.set("n", "<leader>lf", function() vim.keymap.set("n", "<leader>lf", function()
util.format({ util.format({
buf = bufnr, buf = bufnr,
+1 -1
View File
@@ -12,7 +12,7 @@ return {
"--enable-config", "--enable-config",
}, },
single_file_support = true, single_file_support = true,
on_attach = function(client, bufnr) on_attach = function(_, bufnr)
Linter.add(bufnr, { Linter.add(bufnr, {
cmd = { cmd = {
"clang-tidy", "clang-tidy",
+42 -12
View File
@@ -1,5 +1,3 @@
local lsp = require("lsp")
local lua_library_paths = { vim.env.VIMRUNTIME } local lua_library_paths = { vim.env.VIMRUNTIME }
vim.list_extend(lua_library_paths, require("pack").get_paths()) vim.list_extend(lua_library_paths, require("pack").get_paths())
@@ -7,17 +5,17 @@ vim.list_extend(lua_library_paths, require("pack").get_paths())
return { return {
settings = { settings = {
emmylua = { emmylua = {
format = { diagnostics = {
useDiff = true, disable = {
externalTool = { "unnecessary-if",
program = "luafmt", "preferred-local-alias",
args = { "redefined-local",
"--stdin",
"--level=lua-jit",
"--config=.luafmt.toml",
}
}, },
}, },
format = {
-- Re-enable once luafmt is integrated in server
-- useDiff = true,
},
runtime = { runtime = {
version = "LuaJIT", version = "LuaJIT",
requirePattern = { requirePattern = {
@@ -33,5 +31,37 @@ return {
}, },
} }
}, },
on_attach = lsp.on_attach, on_attach = function(_, bufnr)
local util = require("util")
vim.keymap.set("n", "<leader>lf", function()
util.format({
buf = bufnr,
cmd = {
"stylua",
"--stdin-filepath",
"%file%",
"-",
},
output = "stdout",
})
end, { buffer = bufnr })
vim.keymap.set("x", "<leader>lf", function()
util.format({
buf = bufnr,
cmd = {
"stylua",
"--range-start",
"%byte_start%",
"--range-end",
"%byte_end%",
"--stdin-filepath",
"%file%",
"-",
},
output = "stdout",
})
end, { buffer = bufnr })
end,
} }
+1 -1
View File
@@ -11,7 +11,7 @@ return {
}, },
}, },
}, },
on_attach = function(client, bufnr) on_attach = function(_, bufnr)
vim.keymap.set("n", "<leader>lf", function() vim.keymap.set("n", "<leader>lf", function()
util.format({ util.format({
buf = bufnr, buf = bufnr,
+1 -1
View File
@@ -11,7 +11,7 @@ return {
}, },
}, },
}, },
on_attach = function(client, bufnr) on_attach = function(_, bufnr)
Linter.add(bufnr, { Linter.add(bufnr, {
cmd = { cmd = {
"phpcs", "phpcs",
-73
View File
@@ -1,73 +0,0 @@
local lua_library_paths = { vim.env.VIMRUNTIME }
vim.list_extend(lua_library_paths, require("pack").get_paths())
---@type vim.lsp.Config
return {
settings = {
Lua = {
codeLens = {
enable = true,
},
completion = {
callSnippet = "Replace",
keywordSnippet = "Replace",
showWord = "Disable",
},
runtime = {
version = "LuaJIT",
path = {
"lua/?.lua",
"lua/?/init.lua",
},
pathStrict = true,
},
workspace = {
library = lua_library_paths,
checkThirdParty = false,
},
hint = {
enable = false,
arrayIndex = "Disable",
await = true,
paramName = "All",
paramType = true,
semicolon = "Disable",
setType = true,
},
telemetry = { enable = false },
},
},
on_attach = function(_, bufnr)
local util = require("util")
vim.keymap.set("n", "<leader>lf", function()
util.format({
buf = bufnr,
cmd = {
"stylua",
"--stdin-filepath",
"%file%",
"-",
},
output = "stdout",
})
end, { buffer = bufnr })
vim.keymap.set("x", "<leader>lf", function()
util.format({
buf = bufnr,
cmd = {
"stylua",
"--range-start",
"%byte_start%",
"--range-end",
"%byte_end%",
"--stdin-filepath",
"%file%",
"-",
},
output = "stdout",
})
end, { buffer = bufnr })
end,
}
+1 -1
View File
@@ -2,7 +2,7 @@ local util = require("util")
---@type vim.lsp.Config ---@type vim.lsp.Config
return { return {
on_attach = function(client, bufnr) on_attach = function(_, bufnr)
vim.keymap.set("n", "<leader>lf", function() vim.keymap.set("n", "<leader>lf", function()
vim.lsp.buf.format() vim.lsp.buf.format()
util.format({ util.format({
+1
View File
@@ -15,6 +15,7 @@ for _, file in ipairs(files) do
local pkg = "core." .. file local pkg = "core." .. file
local ok, err = pcall(require, pkg) local ok, err = pcall(require, pkg)
if not ok then if not ok then
---@cast err string
log.error("Error while loading package " .. pkg) log.error("Error while loading package " .. pkg)
log.error(err) log.error(err)
return return
+1 -1
View File
@@ -11,7 +11,7 @@ vim.api.nvim_create_user_command("PluginUnwatch", function()
end, { desc = "Stop watching plugin configs" }) end, { desc = "Stop watching plugin configs" })
vim.api.nvim_create_user_command("PluginReload", function(opts) vim.api.nvim_create_user_command("PluginReload", function(opts)
require("pack").reload(opts.args) require("pack").reload_plugin(opts.args)
end, { end, {
nargs = 1, nargs = 1,
complete = function(lead) complete = function(lead)
+4 -2
View File
@@ -58,9 +58,11 @@ local function delete_buffer(force)
if #buffers < 2 then if #buffers < 2 then
return return
end end
local b1 = assert(buffers[1])
local b2 = assert(buffers[2])
local current = tonumber(buffers[1]:match("^%s*(%d+)")) local current = tonumber(b1:match("^%s*(%d+)")) --[[@as integer?]]
local previous = tonumber(buffers[2]:match("^%s*(%d+)")) local previous = tonumber(b2:match("^%s*(%d+)")) --[[@as integer?]]
if not current or not previous then if not current or not previous then
return return
+1
View File
@@ -26,6 +26,7 @@ vim.opt.foldlevel = 99
vim.opt.foldlevelstart = 99 vim.opt.foldlevelstart = 99
vim.opt.foldmethod = "indent" vim.opt.foldmethod = "indent"
vim.opt.foldignore = "" vim.opt.foldignore = ""
---@diagnostic disable-next-line: assign-type-mismatch
vim.opt.completeopt = { vim.opt.completeopt = {
"menu", "menu",
"menuone", "menuone",
+1
View File
@@ -69,6 +69,7 @@ function Content:add_with_treesitter(text, lang)
if not ok or not parser then if not ok or not parser then
return return
end end
---@cast parser vim.treesitter.LanguageTree
local trees = parser:parse() local trees = parser:parse()
if not trees then if not trees then
+9 -10
View File
@@ -91,7 +91,8 @@ end
---@field worktree string ---@field worktree string
---@field buffers integer[] ---@field buffers integer[]
---@field watcher? uv.uv_fs_event_t ---@field watcher? uv.uv_fs_event_t
---@field refresh fun() | ow.Util.Debouncer ---@field refresh fun(self: ow.Git.Repo)
---@field refresh_handle ow.Util.DebounceHandle
local Repo = {} local Repo = {}
Repo.__index = Repo Repo.__index = Repo
@@ -101,13 +102,13 @@ function Repo:start_watcher()
if err or (filename ~= "index" and filename ~= "HEAD") then if err or (filename ~= "index" and filename ~= "HEAD") then
return return
end end
self.refresh() self:refresh()
end)) end))
self.watcher = watcher self.watcher = watcher
end end
function Repo:stop_watcher() function Repo:stop_watcher()
self.refresh:cancel() self.refresh_handle.close()
if self.watcher then if self.watcher then
self.watcher:stop() self.watcher:stop()
self.watcher:close() self.watcher:close()
@@ -179,9 +180,7 @@ function Repo.new(gitdir, worktree)
worktree = worktree, worktree = worktree,
buffers = {}, buffers = {},
}, Repo) }, Repo)
self.refresh = util.debounce(function() self.refresh, self.refresh_handle = util.debounce(do_refresh, 50)
do_refresh(self)
end, 50)
self:start_watcher() self:start_watcher()
return self return self
end end
@@ -232,7 +231,7 @@ local function unregister(buf)
end end
---@param buf integer ---@param buf integer
local function refresh(buf) local function refresh_buf(buf)
if not vim.api.nvim_buf_is_valid(buf) or vim.bo[buf].buftype ~= "" then if not vim.api.nvim_buf_is_valid(buf) or vim.bo[buf].buftype ~= "" then
return return
end end
@@ -241,7 +240,7 @@ local function refresh(buf)
vim.b[buf].git_status = nil vim.b[buf].git_status = nil
return return
end end
repo.refresh() repo:refresh()
end end
local M = {} local M = {}
@@ -260,7 +259,7 @@ function M.setup()
{ {
group = group, group = group,
callback = function(args) callback = function(args)
refresh(args.buf) refresh_buf(args.buf)
end, end,
} }
) )
@@ -273,7 +272,7 @@ function M.setup()
vim.api.nvim_create_autocmd("FocusGained", { vim.api.nvim_create_autocmd("FocusGained", {
group = group, group = group,
callback = function() callback = function()
refresh(vim.api.nvim_get_current_buf()) refresh_buf(vim.api.nvim_get_current_buf())
end, end,
}) })
vim.api.nvim_create_autocmd("VimLeavePre", { vim.api.nvim_create_autocmd("VimLeavePre", {
+22 -17
View File
@@ -46,7 +46,7 @@ local util = require("util")
---@field pattern? string ---@field pattern? string
--- Named capture groups for pattern matching (required if not using json) --- Named capture groups for pattern matching (required if not using json)
---@field groups? ow.lsp.linter.Group[] ---@field groups? ow.lsp.linter.Group[]
--- Map severity strings to vim diagnostic levels --- Map severity strings to vim diagnostic levels (required if not using json)
---@field severity_map? table<string, vim.diagnostic.Severity> ---@field severity_map? table<string, vim.diagnostic.Severity>
--- Source name for diagnostics (default: command name) --- Source name for diagnostics (default: command name)
---@field source? string ---@field source? string
@@ -131,17 +131,13 @@ function Linter:add_tags(diag)
return return
end end
local have_unnecessary = vim.islist(self.config.tags.unnecessary) diag._tags = {
local have_deprecated = vim.islist(self.config.tags.deprecated) unnecessary = false,
deprecated = false,
if not have_unnecessary and not have_deprecated then }
return
end
diag._tags = {}
if if
have_unnecessary self.config.tags.unnecessary
and vim.list_contains(self.config.tags.unnecessary, diag.code) and vim.list_contains(self.config.tags.unnecessary, diag.code)
then then
diag._tags.unnecessary = true diag._tags.unnecessary = true
@@ -149,7 +145,7 @@ function Linter:add_tags(diag)
end end
if if
have_deprecated self.config.tags.deprecated
and vim.list_contains(self.config.tags.deprecated, diag.code) and vim.list_contains(self.config.tags.deprecated, diag.code)
then then
diag._tags.deprecated = true diag._tags.deprecated = true
@@ -181,13 +177,15 @@ function Linter:fix_indexing(diag)
end end
end end
---@param json any
function Linter:process_json_output(json) function Linter:process_json_output(json)
---@type vim.Diagnostic[] ---@type vim.Diagnostic[]
local diagnostics = {} local diagnostics = {}
local cfg = assert(self.config.json)
local items = json local items = json
if self.config.json.diagnostics_root then if cfg.diagnostics_root then
items = Linter.get_json_value(json, self.config.json.diagnostics_root) items = Linter.get_json_value(json, cfg.diagnostics_root)
end end
if type(items) ~= "table" then if type(items) ~= "table" then
@@ -202,8 +200,9 @@ function Linter:process_json_output(json)
for _, item in ipairs(items) do for _, item in ipairs(items) do
local diag = {} local diag = {}
for field, path in pairs(self.config.json) do for field, path in pairs(cfg) do
if field ~= "diagnostics_root" and field ~= "callback" then if field ~= "diagnostics_root" and field ~= "callback" then
---@cast path string
diag[field] = Linter.get_json_value(item, path) diag[field] = Linter.get_json_value(item, path)
end end
end end
@@ -218,12 +217,14 @@ function Linter:process_json_output(json)
diag.severity = self.config.severity_map[diag.severity] diag.severity = self.config.severity_map[diag.severity]
end end
---@cast diag vim.Diagnostic
self:fix_indexing(diag) self:fix_indexing(diag)
self:clamp_col(diag) self:clamp_col(diag)
self:add_tags(diag) self:add_tags(diag)
if type(self.config.json.callback) == "function" then if type(cfg.callback) == "function" then
self.config.json.callback(diag) cfg.callback(diag)
end end
table.insert(diagnostics, diag) table.insert(diagnostics, diag)
@@ -371,6 +372,9 @@ function Linter:run()
return return
end end
---@cast self.config.pattern -nil
---@cast self.config.groups -nil
---@cast self.config.severity_map -nil
local diagnostics = {} local diagnostics = {}
for _, line in ipairs(lines) do for _, line in ipairs(lines) do
@@ -387,6 +391,7 @@ function Linter:run()
success = false success = false
return return
elseif resp then elseif resp then
---@cast resp vim.Diagnostic
resp.source = resp.source or self.config.source resp.source = resp.source or self.config.source
self:clamp_col(resp) self:clamp_col(resp)
self:add_tags(resp) self:add_tags(resp)
@@ -439,7 +444,7 @@ function Linter.add(bufnr, config)
buffer = linter.bufnr, buffer = linter.bufnr,
callback = util.debounce(function() callback = util.debounce(function()
linter:run() linter:run()
end, config.debounce) --[[@as fun()]], end, config.debounce),
group = linter.augroup, group = linter.augroup,
}) })
+10 -23
View File
@@ -7,23 +7,13 @@ local log = require("log")
local GROUP = vim.api.nvim_create_augroup("ow.lsp.codelens", { clear = true }) local GROUP = vim.api.nvim_create_augroup("ow.lsp.codelens", { clear = true })
---@type table<integer, ow.lsp.codelens.Session>
local session_by_buf = {}
local M = {} local M = {}
---@param buf integer
---@return ow.lsp.codelens.Session
local function get_session(buf)
session_by_buf[buf] = session_by_buf[buf] or Session.new(buf)
return session_by_buf[buf]
end
---@param buf? integer ---@param buf? integer
---@return boolean ---@return boolean
function M.is_enabled(buf) function M.is_enabled(buf)
buf = buf or vim.api.nvim_get_current_buf() buf = buf or vim.api.nvim_get_current_buf()
local session = session_by_buf[buf] local session = Session.find(buf)
return session ~= nil and session.enabled return session ~= nil and session.enabled
end end
@@ -34,13 +24,13 @@ function M.enable(value, buf)
value = true value = true
end end
buf = buf or vim.api.nvim_get_current_buf() buf = buf or vim.api.nvim_get_current_buf()
get_session(buf):enable(value) Session.get(buf):enable(value)
end end
---@param buf? integer ---@param buf? integer
function M.toggle(buf) function M.toggle(buf)
buf = buf or vim.api.nvim_get_current_buf() buf = buf or vim.api.nvim_get_current_buf()
get_session(buf):toggle() Session.get(buf):toggle()
end end
---@class ow.lsp.codelens.SetupOpts : ow.lsp.codelens.row.ConfigureOpts ---@class ow.lsp.codelens.SetupOpts : ow.lsp.codelens.row.ConfigureOpts
@@ -49,17 +39,18 @@ end
function M.setup(opts) function M.setup(opts)
Row.configure(opts or {}) Row.configure(opts or {})
local method = vim.lsp.protocol.Methods.workspace_codeLens_refresh ---@param err lsp.ResponseError?
vim.lsp.handlers[method] = function(err, _, ctx) ---@param ctx lsp.HandlerContext
vim.lsp.handlers["workspace/codeLens/refresh"] = function(err, _, ctx)
if err then if err then
log.warning( log.warning(
"client %d: error on %s: %s", "client %d: error on %s: %s",
ctx.client_id, ctx.client_id,
method, ctx.method,
err.message err.message
) )
end end
for buf, session in pairs(session_by_buf) do for buf, session in pairs(Session.all()) do
if if
session.enabled session.enabled
and #vim.lsp.get_clients({ bufnr = buf, id = ctx.client_id }) and #vim.lsp.get_clients({ bufnr = buf, id = ctx.client_id })
@@ -74,7 +65,7 @@ function M.setup(opts)
vim.api.nvim_create_autocmd({ "BufEnter", "LspAttach" }, { vim.api.nvim_create_autocmd({ "BufEnter", "LspAttach" }, {
group = GROUP, group = GROUP,
callback = function(ev) callback = function(ev)
local session = session_by_buf[ev.buf] local session = Session.find(ev.buf)
if session and session.enabled then if session and session.enabled then
session:refresh() session:refresh()
end end
@@ -84,11 +75,7 @@ function M.setup(opts)
vim.api.nvim_create_autocmd({ "BufDelete", "BufWipeout" }, { vim.api.nvim_create_autocmd({ "BufDelete", "BufWipeout" }, {
group = GROUP, group = GROUP,
callback = function(ev) callback = function(ev)
local session = session_by_buf[ev.buf] Session.remove(ev.buf)
if session then
session:abort()
end
session_by_buf[ev.buf] = nil
end, end,
}) })
end end
+19 -26
View File
@@ -15,7 +15,8 @@ function RefreshTask.new(session)
session = session, session = session,
aborted = false, aborted = false,
cancels = {}, cancels = {},
}, RefreshTask) },
RefreshTask)
end end
---@param cancel fun() ---@param cancel fun()
@@ -35,20 +36,19 @@ end
---@param lens lsp.CodeLens ---@param lens lsp.CodeLens
---@param row ow.lsp.codelens.Row ---@param row ow.lsp.codelens.Row
function RefreshTask:resolve(client, lens, row) function RefreshTask:resolve(client, lens, row)
local method = vim.lsp.protocol.Methods.codeLens_resolve
local _, req_id = client:request( local _, req_id = client:request(
method, "codeLens/resolve",
lens, lens,
---@param err lsp.ResponseError?
---@param resolved lsp.CodeLens? ---@param resolved lsp.CodeLens?
function(err, resolved) ---@param ctx lsp.HandlerContext
function(err, resolved, ctx)
if self.aborted then if self.aborted then
return return
end end
if err then if err then
log.warning( log.warning(
"client %d: %s failed: %s", "client %d: %s failed: %s", client.id, ctx.method,
client.id,
method,
err.message err.message
) )
end end
@@ -77,33 +77,27 @@ function RefreshTask:process_lens(rows, client, lens)
row:add(lens) row:add(lens)
return return
end end
if if not client or not client:supports_method("codeLens/resolve") then
not client
or not client:supports_method(vim.lsp.protocol.Methods.codeLens_resolve)
then
return return
end end
row:expect() row:expect()
self:resolve(client, lens, row) self:resolve(client, lens, row)
end end
---@param responses table<integer, ow.lsp.CodeLensResponse> ---@param results table<integer, ow.lsp.CodeLensResponse>
function RefreshTask:process_responses(responses) function RefreshTask:process_results(results)
local method = vim.lsp.protocol.Methods.textDocument_codeLens
local session = self.session local session = self.session
local new_rows = {} local new_rows = {}
for client_id, response in pairs(responses) do for client_id, result in pairs(results) do
if response.err then if result.err then
log.warning( log.warning(
"client %d: %s failed: %s", "client %d: %s failed: %s", client_id, result.context.method,
client_id, result.err.message
method,
response.err.message
) )
end end
if not response.err and type(response.result) == "table" then if not result.err and type(result.result) == "table" then
local client = vim.lsp.get_client_by_id(client_id) local client = vim.lsp.get_client_by_id(client_id)
for _, lens in ipairs(response.result) do for _, lens in ipairs(result.result) do
self:process_lens(new_rows, client, lens) self:process_lens(new_rows, client, lens)
end end
end end
@@ -113,19 +107,18 @@ function RefreshTask:process_responses(responses)
end end
function RefreshTask:run() function RefreshTask:run()
local method = vim.lsp.protocol.Methods.textDocument_codeLens
local params = { local params = {
textDocument = vim.lsp.util.make_text_document_params(self.session.buf), textDocument = vim.lsp.util.make_text_document_params(self.session.buf),
} }
local cancel = vim.lsp.buf_request_all( local cancel = vim.lsp.buf_request_all(
self.session.buf, self.session.buf,
method, "textDocument/codeLens",
params, params,
function(responses) function(results)
if self.aborted then if self.aborted then
return return
end end
self:process_responses(responses) self:process_results(results)
end end
) )
self:track(cancel) self:track(cancel)
+18 -7
View File
@@ -6,9 +6,12 @@ local NS = vim.api.nvim_create_namespace("ow.lsp.codelens")
local position = "above" local position = "above"
local separator = " | " local separator = " | "
---@class ow.lsp.CodeLens : lsp.CodeLens
---@field command lsp.Command
---@class ow.lsp.codelens.Row ---@class ow.lsp.codelens.Row
---@field row integer ---@field row integer
---@field lenses lsp.CodeLens[] ---@field lenses ow.lsp.CodeLens[]
---@field pending integer ---@field pending integer
local Row = {} local Row = {}
Row.__index = Row Row.__index = Row
@@ -19,7 +22,7 @@ function Row.new(row)
return setmetatable({ row = row, lenses = {}, pending = 0 }, Row) return setmetatable({ row = row, lenses = {}, pending = 0 }, Row)
end end
---@param lens lsp.CodeLens ---@param lens ow.lsp.CodeLens
function Row:add(lens) function Row:add(lens)
table.insert(self.lenses, lens) table.insert(self.lenses, lens)
end end
@@ -31,8 +34,8 @@ end
---@param lens? lsp.CodeLens ---@param lens? lsp.CodeLens
function Row:resolve(lens) function Row:resolve(lens)
self.pending = self.pending - 1 self.pending = self.pending - 1
if lens then if lens and lens.command then
table.insert(self.lenses, lens) self:add(lens)
end end
end end
@@ -58,7 +61,9 @@ function Row:render(buf)
end end
end end
local col, opts ---@type vim.api.keyset.set_extmark
local opts
local col
if position == "above" then if position == "above" then
local line = vim.api.nvim_buf_get_lines( local line = vim.api.nvim_buf_get_lines(
buf, buf,
@@ -79,7 +84,8 @@ function Row:render(buf)
hl_mode = "combine", hl_mode = "combine",
} }
else else
col = position == "inline" and self.lenses[1].range.start.character or 0 local first = assert(self.lenses[1])
col = position == "inline" and first.range.start.character or 0
opts = { opts = {
virt_text = parts, virt_text = parts,
virt_text_pos = position, virt_text_pos = position,
@@ -97,6 +103,11 @@ function Row:render(buf)
{ self.row, -1 }, { self.row, -1 },
{ details = true } { details = true }
) )
---@type {
--- id: integer,
--- col: integer,
--- details: vim.api.keyset.extmark_details?
---}
local primary local primary
for i, mark in ipairs(marks) do for i, mark in ipairs(marks) do
if i == 1 then if i == 1 then
@@ -107,7 +118,7 @@ function Row:render(buf)
end end
if primary and primary.col == col and primary.details then if primary and primary.col == col and primary.details then
local d = primary.details --[[@as vim.api.keyset.extmark_details]] local d = primary.details
local same = opts.virt_lines local same = opts.virt_lines
and vim.deep_equal(d.virt_lines, opts.virt_lines) and vim.deep_equal(d.virt_lines, opts.virt_lines)
and d.virt_lines_above == opts.virt_lines_above and d.virt_lines_above == opts.virt_lines_above
+41 -13
View File
@@ -13,9 +13,13 @@ local REFRESH_DEBOUNCE_MS = 200
local Session = {} local Session = {}
Session.__index = Session Session.__index = Session
---@param session ow.lsp.codelens.Session ---@type table<integer, ow.lsp.codelens.Session>
local function do_refresh(session) local by_buf = {}
if not session.enabled then
---@param buf integer
local function do_refresh(buf)
local session = by_buf[buf]
if not session or not session.enabled then
return return
end end
session:abort() session:abort()
@@ -24,21 +28,45 @@ local function do_refresh(session)
task:run() task:run()
end end
local refresher = util.keyed_debounce(do_refresh, REFRESH_DEBOUNCE_MS) local refresh, refresh_handle =
util.keyed_debounce(do_refresh, REFRESH_DEBOUNCE_MS)
---@param buf integer ---@param buf integer
---@return ow.lsp.codelens.Session ---@return ow.lsp.codelens.Session
function Session.new(buf) function Session.get(buf)
return setmetatable({ if not by_buf[buf] then
buf = buf, by_buf[buf] = setmetatable({
enabled = false, buf = buf,
attached = false, enabled = false,
rows = {}, attached = false,
}, Session) rows = {},
}, Session)
end
return by_buf[buf]
end
---@param buf integer
---@return ow.lsp.codelens.Session?
function Session.find(buf)
return by_buf[buf]
end
---@return table<integer, ow.lsp.codelens.Session>
function Session.all()
return by_buf
end
---@param buf integer
function Session.remove(buf)
local session = by_buf[buf]
if session then
session:abort()
end
by_buf[buf] = nil
end end
function Session:abort() function Session:abort()
refresher:cancel(self) refresh_handle.cancel(self.buf)
if self.current then if self.current then
self.current:abort() self.current:abort()
self.current = nil self.current = nil
@@ -46,7 +74,7 @@ function Session:abort()
end end
function Session:refresh() function Session:refresh()
refresher(self) refresh(self.buf)
end end
function Session:render() function Session:render()
+55 -52
View File
@@ -10,11 +10,7 @@ local popup = Popup.new()
---@param client vim.lsp.Client ---@param client vim.lsp.Client
---@param buf integer ---@param buf integer
local function on_attach(client, buf) local function on_attach(client, buf)
if if not client:supports_method("textDocument/completion") then
not client:supports_method(
vim.lsp.protocol.Methods.textDocument_completion
)
then
return return
end end
@@ -64,26 +60,23 @@ function M.setup()
end end
local ft = vim.bo[ev.buf].filetype local ft = vim.bo[ev.buf].filetype
---@type ow.lsp.completion.Pum ---@type ow.lsp.completion.Pum
local pum = { local pum = {
row = vim.v.event.row, row = vim.v.event.row --[[@as integer]],
col = vim.v.event.col, col = vim.v.event.col --[[@as integer]],
width = vim.v.event.width, width = vim.v.event.width --[[@as integer]],
height = vim.v.event.height, height = vim.v.event.height --[[@as integer]],
scrollbar = vim.v.event.scrollbar, scrollbar = vim.v.event.scrollbar --[[@as boolean]],
} }
if if client:supports_method("completionItem/resolve") then
client:supports_method(
vim.lsp.protocol.Methods.completionItem_resolve
)
then
popup:dispatch_resolve( popup:dispatch_resolve(
client, client,
item, item,
ft, ft,
pum, pum,
completed.word, completed.word or "",
ev.buf ev.buf
) )
else else
@@ -125,22 +118,27 @@ function M.setup()
) )
end end
if raw.command then if raw.command then
local method = client:request(
vim.lsp.protocol.Methods.workspace_executeCommand "workspace/executeCommand",
client:request(method, { {
command = raw.command.command, command = raw.command.command,
arguments = raw.command.arguments, arguments = raw.command.arguments,
}, function(err) },
if err then ---@param err lsp.ResponseError?
log.warning( ---@param ctx lsp.HandlerContext
"client %d: %s failed for %s: %s", function(err, _, ctx)
client.id, if err then
method, log.warning(
raw.command.title, "client %d: %s failed for %s: %s",
err.message client.id,
) ctx.method,
end raw.command.title,
end, ev.buf) err.message
)
end
end,
ev.buf
)
end end
if target.snippet then if target.snippet then
local word = completed.word or "" local word = completed.word or ""
@@ -161,32 +159,37 @@ function M.setup()
-- Prefer the resolved item when we have it. If we haven't cached -- Prefer the resolved item when we have it. If we haven't cached
-- one yet and the original is missing edits, resolve on the fly. -- one yet and the original is missing edits, resolve on the fly.
local cached = popup:resolved_for(completed.word) local cached = popup:resolved_for(completed.word or "")
if cached then if cached then
apply(cached) apply(cached)
elseif elseif
client:supports_method( client:supports_method("completionItem/resolve")
vim.lsp.protocol.Methods.completionItem_resolve
)
and not item.raw.additionalTextEdits and not item.raw.additionalTextEdits
and not item.raw.command and not item.raw.command
then then
local method = vim.lsp.protocol.Methods.completionItem_resolve client:request(
client:request(method, item.raw, function(err, resolved) "completionItem/resolve",
if err then item.raw,
log.warning( ---@param err lsp.ResponseError?
"client %d: %s failed: %s", ---@param resolved lsp.CompletionItem?
client.id, ---@param ctx lsp.HandlerContext
method, function(err, resolved, ctx)
err.message if err then
) log.warning(
end "client %d: %s failed: %s",
if err or not resolved then client.id,
return ctx.method,
end err.message
item:apply_resolved(resolved) )
apply(item) end
end, ev.buf) if err or not resolved then
return
end
item:apply_resolved(resolved)
apply(item)
end,
ev.buf
)
else else
apply(item) apply(item)
end end
+77 -53
View File
@@ -81,15 +81,24 @@ function Popup:resolved_for(word)
return nil return nil
end end
---@return integer?
function Popup:active_win()
if self.winid and vim.api.nvim_win_is_valid(self.winid) then
return self.winid
end
return nil
end
---@return boolean ---@return boolean
function Popup:is_visible() function Popup:is_visible()
return self.winid ~= nil and vim.api.nvim_win_is_valid(self.winid) return self:active_win() ~= nil
end end
function Popup:close() function Popup:close()
self:cancel_pending() self:cancel_pending()
if self:is_visible() then local winid = self:active_win()
vim.api.nvim_win_close(self.winid, true) if winid then
vim.api.nvim_win_close(winid, true)
end end
self.winid = nil self.winid = nil
end end
@@ -115,28 +124,35 @@ end
function Popup:dispatch_resolve(client, item, ft, pum, word, buf) function Popup:dispatch_resolve(client, item, ft, pum, word, buf)
self:cancel_pending() self:cancel_pending()
self.resolved = nil self.resolved = nil
local method = vim.lsp.protocol.Methods.completionItem_resolve local _, request_id = client:request(
local _, request_id = client:request(method, item.raw, function(err, result) "completionItem/resolve",
if err then item.raw,
log.warning( ---@param err lsp.ResponseError?
"client %d: %s failed: %s", ---@param result lsp.CompletionItem?
client.id, ---@param ctx lsp.HandlerContext
method, function(err, result, ctx)
err.message if err then
) log.warning(
end "client %d: %s failed: %s",
self.pending = nil client.id,
if err or not result then ctx.method,
return err.message
end )
local cur = vim.fn.complete_info({ "completed" }) end
if (vim.tbl_get(cur, "completed", "word") or "") ~= word then self.pending = nil
return if err or not result then
end return
item:apply_resolved(result) end
self.resolved = { word = word, item = item } local cur = vim.fn.complete_info({ "completed" })
self:show(item, ft, pum) if (vim.tbl_get(cur, "completed", "word") or "") ~= word then
end, buf) return
end
item:apply_resolved(result)
self.resolved = { word = word, item = item }
self:show(item, ft, pum)
end,
buf
)
if request_id then if request_id then
self.pending = { client = client, id = request_id } self.pending = { client = client, id = request_id }
end end
@@ -148,14 +164,14 @@ Popup.HALF_PAGE = HALF_HEIGHT
---@param pum ow.lsp.completion.Pum ---@param pum ow.lsp.completion.Pum
---@param width integer ---@param width integer
function Popup:render(content, pum, width) function Popup:render(content, pum, width)
self:ensure_buffer() local bufnr = self:ensure_buffer()
local lines = vim.split(content, "\n", { plain = true }) local lines = vim.split(content, "\n", { plain = true })
vim.api.nvim_buf_set_lines(self.bufnr, 0, -1, false, lines) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
vim.api.nvim_buf_clear_namespace(self.bufnr, NS, 0, -1) vim.api.nvim_buf_clear_namespace(bufnr, NS, 0, -1)
for i, line in ipairs(lines) do for i, line in ipairs(lines) do
if line ~= "" and line:gsub("", "") == "" then if line ~= "" and line:gsub("", "") == "" then
vim.api.nvim_buf_set_extmark(self.bufnr, NS, i - 1, 0, { vim.api.nvim_buf_set_extmark(bufnr, NS, i - 1, 0, {
end_row = i - 1, end_row = i - 1,
end_col = #line, end_col = #line,
hl_group = "FloatBorder", hl_group = "FloatBorder",
@@ -187,22 +203,24 @@ function Popup:render(content, pum, width)
style = "minimal", style = "minimal",
} }
if self:is_visible() then local winid = self:active_win()
vim.api.nvim_win_set_config(self.winid, cfg) if winid then
vim.api.nvim_win_set_config(winid, cfg)
else else
cfg.noautocmd = true cfg.noautocmd = true
self.winid = vim.api.nvim_open_win(self.bufnr, false, cfg) winid = vim.api.nvim_open_win(bufnr, false, cfg)
vim.wo[self.winid].wrap = true self.winid = winid
vim.wo[self.winid].linebreak = true vim.wo[winid].wrap = true
vim.wo[self.winid].conceallevel = 2 vim.wo[winid].linebreak = true
vim.wo[winid].conceallevel = 2
end end
vim.api.nvim_win_set_cursor(self.winid, { 1, 0 }) vim.api.nvim_win_set_cursor(winid, { 1, 0 })
local actual = vim.api.nvim_win_text_height(self.winid, { local actual = vim.api.nvim_win_text_height(winid, {
max_height = MAX_HEIGHT, max_height = MAX_HEIGHT,
}).all }).all
if actual ~= height then if actual ~= height then
vim.api.nvim_win_set_height(self.winid, actual) vim.api.nvim_win_set_height(winid, actual)
end end
self:update_indicators() self:update_indicators()
@@ -211,12 +229,13 @@ end
---@param direction "up" | "down" ---@param direction "up" | "down"
---@param count integer ---@param count integer
function Popup:scroll(direction, count) function Popup:scroll(direction, count)
if not self:is_visible() then local winid = self:active_win()
if not winid then
return return
end end
local key = direction == "down" and vim.keycode("<C-e>") local key = direction == "down" and vim.keycode("<C-e>")
or vim.keycode("<C-y>") or vim.keycode("<C-y>")
vim.api.nvim_win_call(self.winid, function() vim.api.nvim_win_call(winid, function()
vim.cmd.normal({ args = { count .. key }, bang = true }) vim.cmd.normal({ args = { count .. key }, bang = true })
end) end)
self:update_indicators() self:update_indicators()
@@ -229,46 +248,51 @@ function Popup:cancel_pending()
end end
end end
---@return integer
function Popup:ensure_buffer() function Popup:ensure_buffer()
if self.bufnr and vim.api.nvim_buf_is_valid(self.bufnr) then if self.bufnr and vim.api.nvim_buf_is_valid(self.bufnr) then
return return self.bufnr
end end
self.bufnr = vim.api.nvim_create_buf(false, true) local bufnr = vim.api.nvim_create_buf(false, true)
vim.bo[self.bufnr].buftype = "nofile" vim.bo[bufnr].buftype = "nofile"
vim.bo[self.bufnr].bufhidden = "hide" vim.bo[bufnr].bufhidden = "hide"
vim.bo[self.bufnr].swapfile = false vim.bo[bufnr].swapfile = false
-- Markdown parser may not be installed; fall back to no highlighting. -- Markdown parser may not be installed; fall back to no highlighting.
pcall(vim.treesitter.start, self.bufnr, "markdown") pcall(vim.treesitter.start, bufnr, "markdown")
self.bufnr = bufnr
return bufnr
end end
function Popup:update_indicators() function Popup:update_indicators()
if not self:is_visible() then local winid = self:active_win()
if not winid then
return return
end end
local visible = vim.api.nvim_win_get_height(self.winid) local visible = vim.api.nvim_win_get_height(winid)
local topline, botline = unpack(vim.api.nvim_win_call(self.winid, function() ---@type integer, integer
local topline, botline = unpack(vim.api.nvim_win_call(winid, function()
return { vim.fn.line("w0"), vim.fn.line("w$") } return { vim.fn.line("w0"), vim.fn.line("w$") }
end)) end))
local display_topline = 1 local display_topline = 1
if topline > 1 then if topline > 1 then
display_topline = vim.api.nvim_win_text_height(self.winid, { display_topline = vim.api.nvim_win_text_height(winid, {
end_row = topline - 2, end_row = topline - 2,
}).all + 1 }).all + 1
end end
local display_bot = display_topline + visible - 1 local display_bot = display_topline + visible - 1
local total = vim.api.nvim_win_text_height(self.winid, { local total = vim.api.nvim_win_text_height(winid, {
max_height = display_bot + 1, max_height = display_bot + 1,
}).all }).all
local has_above = display_topline > 1 local has_above = display_topline > 1
local has_below = display_bot < total local has_below = display_bot < total
and botline and botline
< vim.api.nvim_buf_line_count(vim.api.nvim_win_get_buf(self.winid)) < vim.api.nvim_buf_line_count(vim.api.nvim_win_get_buf(winid))
vim.api.nvim_win_set_config(self.winid, { vim.api.nvim_win_set_config(winid, {
title = has_above and { { "", "FloatBorder" } } or "", title = has_above and { { "", "FloatBorder" } } or "",
title_pos = has_above and "right" or nil, title_pos = has_above and "right" or nil,
footer = has_below and { { "", "FloatBorder" } } or "", footer = has_below and { { "", "FloatBorder" } } or "",
+54 -48
View File
@@ -113,6 +113,7 @@ local function build_items(responses, base)
items = vim.fn.matchfuzzy(items, base, { key = "filter" }) items = vim.fn.matchfuzzy(items, base, { key = "filter" })
else else
items = vim.tbl_filter(function(item) items = vim.tbl_filter(function(item)
---@diagnostic disable-next-line: undefined-field
return vim.startswith(item.filter, base) return vim.startswith(item.filter, base)
end, items) end, items)
end end
@@ -123,7 +124,7 @@ end
local function buffer_has_completion_client() local function buffer_has_completion_client()
return #vim.lsp.get_clients({ return #vim.lsp.get_clients({
bufnr = 0, bufnr = 0,
method = vim.lsp.protocol.Methods.textDocument_completion, method = "textDocument/completion",
}) > 0 }) > 0
end end
@@ -140,7 +141,7 @@ end
local function is_trigger_char(char) local function is_trigger_char(char)
local clients = vim.lsp.get_clients({ local clients = vim.lsp.get_clients({
bufnr = 0, bufnr = 0,
method = vim.lsp.protocol.Methods.textDocument_completion, method = "textDocument/completion",
}) })
for _, client in ipairs(clients) do for _, client in ipairs(clients) do
local chars = vim.tbl_get( local chars = vim.tbl_get(
@@ -199,61 +200,66 @@ function Session:dispatch(trigger_kind, trigger_char, manual)
triggerKind = trigger_kind, triggerKind = trigger_kind,
triggerCharacter = trigger_char, triggerCharacter = trigger_char,
} }
local method = vim.lsp.protocol.Methods.textDocument_completion self.cancel = vim.lsp.buf_request_all(
self.cancel = vim.lsp.buf_request_all(buf, method, params, function(result) buf,
if self.generation ~= gen then "textDocument/completion",
return params,
end function(result, ctx)
vim.schedule(function()
-- Re-check: another dispatch may have fired between response
-- and the scheduled callback running.
if self.generation ~= gen then if self.generation ~= gen then
return return
end end
if vim.fn.mode() ~= "i" then vim.schedule(function()
return -- Re-check: another dispatch may have fired between response
end -- and the scheduled callback running.
local word_start, cursor = word_bounds() if self.generation ~= gen then
if return
not self.manual
and not self.trigger_char
and word_start == cursor
then
return
end
self.is_incomplete = false
for client_id, response in pairs(result) do
if response.err then
log.warning(
"client %d: %s failed: %s",
client_id,
method,
response.err.message
)
end end
local r = response.result if vim.fn.mode() ~= "i" then
if type(r) == "table" and r.isIncomplete then return
self.is_incomplete = true
break
end end
end local word_start, cursor = word_bounds()
local start = word_start if
for _, response in pairs(result) do not self.manual
local pos = edit_start(response) and not self.trigger_char
if pos then and word_start == cursor
start = pos.character then
break return
end end
end self.is_incomplete = false
local base = vim.api.nvim_get_current_line():sub(start + 1, cursor) for client_id, response in pairs(result) do
vim.fn.complete(start + 1, build_items(result, base)) if response.err then
end) log.warning(
end) "client %d: %s failed: %s",
client_id,
ctx.method,
response.err.message
)
end
local r = response.result
if type(r) == "table" and r.isIncomplete then
self.is_incomplete = true
break
end
end
local start = word_start
for _, response in pairs(result) do
local pos = edit_start(response)
if pos then
start = pos.character
break
end
end
local base =
vim.api.nvim_get_current_line():sub(start + 1, cursor)
vim.fn.complete(start + 1, build_items(result, base))
end)
end
)
end end
local session = Session.new() local session = Session.new()
local dispatcher = util.debounce(function(trigger_kind, char) local dispatch = util.debounce(function(trigger_kind, char)
if vim.fn.mode() ~= "i" then if vim.fn.mode() ~= "i" then
return return
end end
@@ -288,7 +294,7 @@ function M.on_insert_char_pre()
local kind_num = is_trigger local kind_num = is_trigger
and vim.lsp.protocol.CompletionTriggerKind.TriggerCharacter and vim.lsp.protocol.CompletionTriggerKind.TriggerCharacter
or vim.lsp.protocol.CompletionTriggerKind.Invoked or vim.lsp.protocol.CompletionTriggerKind.Invoked
dispatcher(kind_num, is_trigger and char or nil) dispatch(kind_num, is_trigger and char or nil)
end end
return M return M
+9
View File
@@ -33,6 +33,15 @@ local function with_file(path, settings)
return return
end end
if type(resp) ~= "table" then
log.warning(
"Invalid json in file %s: expected table, got: %s",
path,
type(resp)
)
return
end
return vim.tbl_deep_extend("force", settings or {}, resp) return vim.tbl_deep_extend("force", settings or {}, resp)
end end
+45 -32
View File
@@ -1,7 +1,11 @@
local log = require("log") local log = require("log")
local util = require("util") local util = require("util")
local plugins_dir = vim.fs.joinpath(vim.fn.stdpath("config"), "plugins") local config_dir = vim.fn.stdpath("config")
if type(config_dir) == "table" then
config_dir = assert(config_dir[1])
end
local plugins_dir = vim.fs.joinpath(config_dir, "plugins")
---@param path string ---@param path string
---@return boolean success ---@return boolean success
@@ -111,7 +115,7 @@ end
---@param plugin ow.Pack.Plugin ---@param plugin ow.Pack.Plugin
local function run_ts_build(plugin) local function run_ts_build(plugin)
local ts = require("ts") local ts = require("ts")
for _, p in ipairs(ts.normalize(plugin.ts_parser)) do for _, p in ipairs(ts.normalize(assert(plugin.ts_parser))) do
ts.build(plugin, p) ts.build(plugin, p)
end end
end end
@@ -149,9 +153,8 @@ end
---@type uv.uv_fs_event_t? ---@type uv.uv_fs_event_t?
local watcher = nil local watcher = nil
---@type ow.Util.KeyedDebounceHandle<string>?
---@type (fun(filename: string) | ow.Util.KeyedDebouncer<string>)? local on_change_handle = nil
local reload = nil
---@class ow.Pack ---@class ow.Pack
---@field plugins ow.Pack.Plugin[] ---@field plugins ow.Pack.Plugin[]
@@ -174,7 +177,7 @@ function M.get_paths()
end end
---@param name string ---@param name string
function M.reload(name) function M.reload_plugin(name)
load(name, true) load(name, true)
end end
@@ -184,29 +187,40 @@ function M.watch()
end end
watcher = assert(vim.uv.new_fs_event()) watcher = assert(vim.uv.new_fs_event())
reload = util.keyed_debounce(function(filename) local on_change, handle = util.keyed_debounce(
local path = vim.fs.joinpath(plugins_dir, filename) ---@param filename string
if not vim.uv.fs_stat(path) then function(filename)
return local path = vim.fs.joinpath(plugins_dir, filename)
end if not vim.uv.fs_stat(path) then
local ok, load_err = exec(path) return
if ok then end
log.info("Reloaded %s", filename) local ok, load_err = exec(path)
else if ok then
log.error("Failed to reload %s: %s", filename, load_err) log.info("Reloaded %s", filename)
end else
end, 100) log.error("Failed to reload %s: %s", filename, load_err)
end
end,
200
)
on_change_handle = handle
assert(watcher:start(plugins_dir, {}, function(err, filename) assert(watcher:start(
if err then plugins_dir,
log.error("Watch error: %s", err) {},
return ---@param err string?
---@param filename string
function(err, filename)
if err then
log.error("Watch error: %s", err)
return
end
if not filename or not filename:match("%.lua$") then
return
end
on_change(filename)
end end
if not filename or not filename:match("%.lua$") then ))
return
end
reload(filename)
end))
end end
function M.unwatch() function M.unwatch()
@@ -214,14 +228,13 @@ function M.unwatch()
return return
end end
if reload then
reload:close()
reload = nil
end
watcher:stop() watcher:stop()
watcher:close() watcher:close()
watcher = nil watcher = nil
if on_change_handle then
on_change_handle.close()
on_change_handle = nil
end
end end
---@param specs (string | ow.Pack.PluginSpec)[] ---@param specs (string | ow.Pack.PluginSpec)[]
+2
View File
@@ -114,9 +114,11 @@ function M.normalize(field)
if type(field) == "table" then if type(field) == "table" then
if type(field.lang) == "string" then if type(field.lang) == "string" then
---@cast field ow.TS.ParserSpec
return { field } return { field }
end end
if type(field[1]) == "table" then if type(field[1]) == "table" then
---@cast field ow.TS.ParserSpec[]
return field return field
end end
end end
+108 -145
View File
@@ -293,167 +293,130 @@ function M.is_list_or_nil(val, t)
end end
end end
---@class ow.Util.Debouncer ---@class ow.Util.DebounceHandle
---@field package _fn fun(...) ---@field cancel fun()
---@field package _delay integer ---@field flush fun()
---@field package _timer uv.uv_timer_t ---@field pending fun(): boolean
---@field package _gen integer ---@field close fun()
---@field package _fired_gen integer
---@field package _args? table
---@field package _cb_main fun()
---@field package _cb_uv fun()
local Debouncer = {}
Debouncer.__index = Debouncer
---@param fn fun(...)
---@param delay integer
---@return ow.Util.Debouncer
function Debouncer.new(fn, delay)
local self = setmetatable({
_fn = fn,
_delay = delay,
_timer = assert(vim.uv.new_timer()),
_gen = 0,
_fired_gen = 0,
_args = nil,
}, Debouncer)
self._cb_main = vim.schedule_wrap(function()
-- Identity check: the libuv fire may have been superseded by a
-- re-arm or a cancel between the timer firing and this scheduled
-- callback running.
if self._fired_gen ~= self._gen or self._args == nil then
return
end
local args = self._args
self._args = nil
self._fn(vim.F.unpack_len(args))
end)
self._cb_uv = function()
self._fired_gen = self._gen
self._cb_main()
end
return self
end
function Debouncer:__call(...)
self._args = vim.F.pack_len(...)
self._gen = self._gen + 1
self._timer:start(self._delay, 0, self._cb_uv)
end
function Debouncer:cancel()
self._timer:stop()
self._args = nil
end
function Debouncer:flush()
if self._args == nil then
return
end
self._timer:stop()
local args = self._args
self._args = nil
self._fn(vim.F.unpack_len(args))
end
---@return boolean
function Debouncer:pending()
return self._args ~= nil
end
function Debouncer:close()
self._timer:stop()
if not self._timer:is_closing() then
self._timer:close()
end
self._args = nil
end
---@generic F: fun(...) ---@generic F: fun(...)
---@param fn F ---@param fn F
---@param delay integer ---@param delay integer
---@return F | ow.Util.Debouncer ---@return F, ow.Util.DebounceHandle
function M.debounce(fn, delay) function M.debounce(fn, delay)
return Debouncer.new(fn, delay) local timer = assert(vim.uv.new_timer())
end local args ---@type table?
local gen = 0
local fired_gen = 0
---@class ow.Util.KeyedDebouncer<T> local cb_main = vim.schedule_wrap(function()
---@field package _fn fun(key: T, ...) -- Identity check: the libuv fire may have been superseded by a
---@field package _delay integer -- re-arm or a cancel between the timer firing and this scheduled
---@field package _slots table<T, ow.Util.Debouncer> -- callback running.
local KeyedDebouncer = {} if fired_gen ~= gen or args == nil then
KeyedDebouncer.__index = KeyedDebouncer return
end
local a = args
args = nil
fn(vim.F.unpack_len(a))
end)
---@generic T local cb_uv = function()
---@param fn fun(key: T, ...) fired_gen = gen
---@param delay integer cb_main()
---@return ow.Util.KeyedDebouncer<T>
function KeyedDebouncer.new(fn, delay)
return setmetatable({
_fn = fn,
_delay = delay,
_slots = {},
}, KeyedDebouncer)
end
---@generic T
---@param self ow.Util.KeyedDebouncer<T>
---@param key T
function KeyedDebouncer:__call(key, ...)
local slot = self._slots[key]
if not slot then
slot = Debouncer.new(function(...)
self._fn(key, ...)
end, self._delay)
self._slots[key] = slot
end end
slot(...)
end
---@generic T local function call(...)
---@param self ow.Util.KeyedDebouncer<T> args = vim.F.pack_len(...)
---@param key T gen = gen + 1
function KeyedDebouncer:cancel(key) timer:start(delay, 0, cb_uv)
local slot = self._slots[key]
if slot then
slot:close()
self._slots[key] = nil
end end
return call,
{
cancel = function()
timer:stop()
args = nil
end,
flush = function()
if args == nil then
return
end
timer:stop()
local a = args
args = nil
fn(vim.F.unpack_len(a))
end,
pending = function()
return args ~= nil
end,
close = function()
timer:stop()
if not timer:is_closing() then
timer:close()
end
args = nil
end,
}
end end
---@generic T ---@class ow.Util.KeyedDebounceHandle<K>
---@param self ow.Util.KeyedDebouncer<T> ---@field cancel fun(key: K)
---@param key T ---@field flush fun(key: K)
function KeyedDebouncer:flush(key) ---@field pending fun(key: K): boolean
local slot = self._slots[key] ---@field close fun()
if slot then
slot:flush()
end
end
---@generic T ---@generic K, F: fun(key: K, ...)
---@param self ow.Util.KeyedDebouncer<T>
---@param key T
---@return boolean
function KeyedDebouncer:pending(key)
local slot = self._slots[key]
return slot ~= nil and slot:pending()
end
function KeyedDebouncer:close()
for _, slot in pairs(self._slots) do
slot:close()
end
self._slots = {}
end
---@diagnostic disable-next-line: undefined-doc-name
---@generic T, F: fun(key: T, ...)
---@param fn F ---@param fn F
---@param delay integer ---@param delay integer
---@return F | ow.Util.KeyedDebouncer<T> ---@return F, ow.Util.KeyedDebounceHandle<K>
function M.keyed_debounce(fn, delay) function M.keyed_debounce(fn, delay)
return KeyedDebouncer.new(fn, delay) ---@type table<K, { call: fun(...), handle: ow.Util.DebounceHandle }>
local slots = {}
local function call(key, ...)
local t = type(key)
assert(
t == "string" or t == "number" or t == "boolean",
"key must be a primitive (string, number, boolean)"
)
local slot = slots[key]
if not slot then
local c, h = M.debounce(function(...)
fn(key, ...)
end, delay)
slot = { call = c, handle = h }
slots[key] = slot
end
slot.call(...)
end
return call,
{
cancel = function(key)
local slot = slots[key]
if slot then
slot.handle.close()
slots[key] = nil
end
end,
flush = function(key)
local slot = slots[key]
if slot then
slot.handle.flush()
end
end,
pending = function(key)
local slot = slots[key]
return slot ~= nil and slot.handle.pending()
end,
close = function()
for _, slot in pairs(slots) do
slot.handle.close()
end
slots = {}
end,
}
end end
function M.get_hl_source(name) function M.get_hl_source(name)
+10 -9
View File
@@ -1,3 +1,4 @@
---@diagnostic disable: param-type-mismatch, missing-fields
local blink = require("blink.cmp") local blink = require("blink.cmp")
blink.setup({ blink.setup({
completion = { completion = {
@@ -32,15 +33,15 @@ blink.setup({
return ctx.label return ctx.label
end, end,
highlight = function(ctx) highlight = function(ctx)
local highlights = { ---@type blink.cmp.DrawHighlight[]
{ local highlights = {}
0, table.insert(highlights, {
#ctx.label, 0,
group = ctx.deprecated #ctx.label,
and "BlinkCmpLabelDeprecated" group = ctx.deprecated
or "BlinkCmpLabel", and "BlinkCmpLabelDeprecated"
}, or "BlinkCmpLabel",
} })
for _, idx in ipairs(ctx.label_matched_indices) do for _, idx in ipairs(ctx.label_matched_indices) do
table.insert(highlights, { table.insert(highlights, {
idx, idx,
+1 -1
View File
@@ -1,4 +1,4 @@
---@diagnostic disable-next-line: missing-fields ---@diagnostic disable-next-line: missing-fields, param-type-mismatch
require("Comment").setup({ require("Comment").setup({
--ignore empty lines --ignore empty lines
ignore = "^$", ignore = "^$",
+4 -1
View File
@@ -9,7 +9,10 @@ require("mason-auto-install").setup({
"cmake-language-server", "cmake-language-server",
dependencies = { "golines" }, dependencies = { "golines" },
}, },
"emmylua_ls", {
"emmylua_ls",
dependencies = { "stylua" },
},
"gopls", "gopls",
"hyprls", "hyprls",
{ {