diff --git a/lua/lsp-toggle/fileutils.lua b/lua/lsp-toggle/fileutils.lua index 7640feb..405ba5f 100644 --- a/lua/lsp-toggle/fileutils.lua +++ b/lua/lsp-toggle/fileutils.lua @@ -43,7 +43,7 @@ function M.produce_path() return string.format('%s/%s.json', M.root_dir, file_name) end ----@param data table +---@param data table ---@return boolean|nil function M.save(data) local path = M.produce_path() @@ -62,7 +62,7 @@ function M.save(data) return true end ----@return table|nil +---@return table|nil function M.load() -- returns lspClients local path = M.produce_path() diff --git a/lua/lsp-toggle/utils.lua b/lua/lsp-toggle/utils.lua index 2fc2042..68730c9 100644 --- a/lua/lsp-toggle/utils.lua +++ b/lua/lsp-toggle/utils.lua @@ -1,8 +1,13 @@ +---@class lsp_toggle.tb_server +---@field enabled boolean +---@field server_name string +---@field is_attached fun(): boolean + local fileutils = require('lsp-toggle.fileutils') local M = {} ----@type table +---@type table M.clients = {} function M.load_all_clients() @@ -14,6 +19,15 @@ function M.load_all_clients() M.clients[client.name] = { enabled = vim.lsp.is_enabled(client.name), server_name = client.name, + is_attached = function() + -- NOTE: Using `pairs()` because it is not a list, strictly + for _, v in pairs(client.attached_buffers) do + if v then + return true + end + end + return false + end, } else M.clients[client.name] = nil diff --git a/lua/lsp-toggle/window.lua b/lua/lsp-toggle/window.lua index 4f07042..3be8394 100644 --- a/lua/lsp-toggle/window.lua +++ b/lua/lsp-toggle/window.lua @@ -5,16 +5,18 @@ local M = {} ---@type string[] M.out_buf_table = {} ----@param clients table +---@param clients table function M.print_display(clients) M.out_buf_table = {} -- NOTE: Using `#clients` is not reliable because `clients` is not list-like for _, tb_server in pairs(clients) do - table.insert( - M.out_buf_table, - (tb_server.enabled and '[x] ' or '[ ] ') .. tb_server.server_name - ) + if tb_server.is_attached() then + table.insert( + M.out_buf_table, + (tb_server.enabled and '[x] ' or '[ ] ') .. tb_server.server_name + ) + end end local safe_fn = vim.schedule_wrap(function() @@ -25,8 +27,6 @@ function M.print_display(clients) safe_fn() end --- BUG: Buffer is not flushed 'when switching buffers' --- using ctrl+o. Will investigate function M.open_window() if M.window_id then return @@ -72,6 +72,20 @@ function M.open_window() --- WARN: Leave the `require('lsp-toggle.toggle')...` as is, or it'll break! vim.keymap.set('n', '', require('lsp-toggle.toggle').handle_toggle, map_opts) + + --- Flush the buffer on `BufLeave` + vim.api.nvim_create_autocmd('BufLeave', { + --- WARN: DON'T CLEAR THE AUGROUP! + group = vim.api.nvim_create_augroup('lsp-toggle', { clear = false }), + callback = function(args) + if not (M.window_buf and vim.api.nvim_buf_is_valid(M.window_buf)) then + return + end + if args.buf ~= M.window_buf then + M.close_window() + end + end, + }) end function M.close_window()