Skip to content

Commit

Permalink
feat: added live-reloading of LSP server configs
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Sep 7, 2022
1 parent eff7473 commit b808c26
Showing 1 changed file with 62 additions and 2 deletions.
64 changes: 62 additions & 2 deletions lua/lsp-settings/lsp.lua
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,26 @@ function M.setup()
return settings_root(...) or root_dir(...)
end
end)

M.create_auto_commands()
end

function M.on_new_config(config, root_dir)
M.setup_server_config(config, root_dir)
M.merge_config(config, root_dir)
if config.name == "jsonls" then
M.setup_jsonls(config)
end
end

function M.setup_server_config(config, root_dir)
function M.merge_config(config, root_dir)
local settings = Settings.new()

if config._lsp_settings then
config.settings = vim.deepcopy(config._lsp_settings)
else
config._lsp_settings = vim.deepcopy(config.settings)
end

settings:merge(config.settings)

Util.for_each_global(function(_, file)
Expand All @@ -42,6 +50,46 @@ function M.setup_server_config(config, root_dir)
config.settings = settings:get()
end

function M.reload_settings(fname)
fname = Util.fqn(fname)

-- clear cached settings for this file
Settings.clear(fname)

local root_dir = Util.fqn(vim.fn.fnamemodify(fname, ":h"))

local is_global = false

Util.for_each_global(function(_, file)
if file == fname then
is_global = true
end
end)

local clients = vim.lsp.get_active_clients()

for _, client in ipairs(clients) do
-- reload this client if the global file changed, or its root dir equals the local one
if is_global or client.config.root_dir == root_dir then
-- re-apply config from any other plugins that were overriding on_new_config
if client.config.on_new_config then
pcall(client.config.on_new_config, client.config, client.config.root_dir)
end

-- notify the lsp server of thr new config
local ok = pcall(client.notify, "workspace/didChangeConfiguration", {
settings = client.config.settings,
})

if ok then
Util.info("Reloaded settings for " .. client.name)
else
Util.error("Reloading settings failed for " .. client.name)
end
end
end
end

function M.setup_jsonls(config)
local options = require("lsp-settings.config").options
local schemas = config.settings.json and config.settings.json.schemas or {}
Expand All @@ -67,4 +115,16 @@ function M.setup_jsonls(config)
})
end

function M.create_auto_commands()
local group = vim.api.nvim_create_augroup("LspSettings", { clear = true })

vim.api.nvim_create_autocmd("BufWritePost", {
pattern = Util.merge({}, Config.options.global_settings, Config.options.local_settings),
group = group,
callback = function(event)
M.reload_settings(event.match)
end,
})
end

return M

0 comments on commit b808c26

Please sign in to comment.