refactor(lua): replace vim.cmd use with API calls (#19283)

Signed-off-by: Raphael <glephunter@gmail.com>
This commit is contained in:
Raphael
2022-07-10 00:40:32 +08:00
committed by GitHub
parent 7dbe6b1a46
commit 6b1a8f23d7
4 changed files with 71 additions and 87 deletions

View File

@@ -1354,50 +1354,12 @@ function M.stylize_markdown(bufnr, contents, opts)
return stripped
end
---@private
--- Creates autocommands to close a preview window when events happen.
---
---@param events table list of events
---@param winnr number window id of preview window
---@param bufnrs table list of buffers where the preview window will remain visible
---@see |autocmd-events|
local function close_preview_autocmd(events, winnr, bufnrs)
local augroup = 'preview_window_' .. winnr
-- close the preview window when entered a buffer that is not
-- the floating window buffer or the buffer that spawned it
vim.cmd(string.format(
[[
augroup %s
autocmd!
autocmd BufEnter * lua vim.lsp.util._close_preview_window(%d, {%s})
augroup end
]],
augroup,
winnr,
table.concat(bufnrs, ',')
))
if #events > 0 then
vim.cmd(string.format(
[[
augroup %s
autocmd %s <buffer> lua vim.lsp.util._close_preview_window(%d)
augroup end
]],
augroup,
table.concat(events, ','),
winnr
))
end
end
---@private
--- Closes the preview window
---
---@param winnr number window id of preview window
---@param bufnrs table|nil optional list of ignored buffers
function M._close_preview_window(winnr, bufnrs)
local function close_preview_window(winnr, bufnrs)
vim.schedule(function()
-- exit if we are in one of ignored buffers
if bufnrs and vim.tbl_contains(bufnrs, api.nvim_get_current_buf()) then
@@ -1405,20 +1367,42 @@ function M._close_preview_window(winnr, bufnrs)
end
local augroup = 'preview_window_' .. winnr
vim.cmd(string.format(
[[
augroup %s
autocmd!
augroup end
augroup! %s
]],
augroup,
augroup
))
api.nvim_del_augroup_by_name(augroup)
pcall(vim.api.nvim_win_close, winnr, true)
end)
end
---@private
--- Creates autocommands to close a preview window when events happen.
---
---@param events table list of events
---@param winnr number window id of preview window
---@param bufnrs table list of buffers where the preview window will remain visible
---@see |autocmd-events|
local function close_preview_autocmd(events, winnr, bufnrs)
local augroup = api.nvim_create_augroup('preview_window_' .. winnr, {
clear = true,
})
-- close the preview window when entered a buffer that is not
-- the floating window buffer or the buffer that spawned it
api.nvim_create_autocmd('BufEnter', {
group = augroup,
callback = function()
close_preview_window(winnr, bufnrs)
end,
})
if #events > 0 then
api.nvim_create_autocmd(events, {
buffer = bufnrs[2],
callback = function()
close_preview_window(winnr)
end,
})
end
end
---@internal
--- Computes size of float needed to show contents (with optional wrapping)
---