|
| 1 | +---Utilities for working with mason-lspconfig.nvim |
| 2 | +--- |
| 3 | +---This module can be loaded with `local astrolsp_mason_lspconfig = require "astrolsp.mason-lspconfig"` |
| 4 | +--- |
| 5 | +---copyright 2025 |
| 6 | +---license GNU General Public License v3.0 |
| 7 | +---@class astrolsp.mason-lspconfig |
| 8 | +local M = {} |
| 9 | + |
| 10 | +local function resolve_config() return require("astrolsp").config.mason_lspconfig or {} end |
| 11 | + |
| 12 | +--- Register a new language server with mason-lspconfig |
| 13 | +---@param server string the server name in lspconfig |
| 14 | +---@param spec AstroLSPMasonLspconfigServer the details for registering the server |
| 15 | +function M.register_server(server, spec) |
| 16 | + local filetype_mappings_avail, filetype_mappings = pcall(require, "mason-lspconfig.mappings.filetype") |
| 17 | + local server_mappings_avail, server_mappings = pcall(require, "mason-lspconfig.mappings.server") |
| 18 | + |
| 19 | + if not (filetype_mappings_avail and server_mappings_avail) then |
| 20 | + vim.notify("Unable to properly load required `mason-lspconfig` modules", vim.log.levels.ERROR) |
| 21 | + end |
| 22 | + |
| 23 | + -- register server in the filetype maps |
| 24 | + local filetypes = spec.filetypes |
| 25 | + if type(filetypes) ~= "table" then filetypes = { filetypes } end |
| 26 | + for _, filetype in ipairs(filetypes) do |
| 27 | + if not filetype_mappings[filetype] then filetype_mappings[filetype] = {} end |
| 28 | + table.insert(filetype_mappings, server) |
| 29 | + end |
| 30 | + -- register the mappings between lspconfig server name and mason package name |
| 31 | + server_mappings.lspconfig_to_package[server] = spec.package |
| 32 | + server_mappings.package_to_lspconfig[spec.package] = server |
| 33 | + -- if a config is provided, set up a mason-lspconfig server configuration module |
| 34 | + if spec.config then |
| 35 | + local module = spec.config |
| 36 | + if type(module) == "table" then |
| 37 | + local orig_function = module |
| 38 | + module = function() return orig_function end |
| 39 | + end |
| 40 | + local module_name = "mason-lspconfig.server_configurations." .. server |
| 41 | + if package.loaded[module_name] == nil then |
| 42 | + package.preload[module_name] = function() return module end |
| 43 | + else |
| 44 | + package.loaded[module_name] = module |
| 45 | + end |
| 46 | + end |
| 47 | +end |
| 48 | + |
| 49 | +--- Register multiple new language servers with mason-lspconfig |
| 50 | +---@param server_specs? AstroLSPMasonLspconfigServers |
| 51 | +function M.register_servers(server_specs) |
| 52 | + if not server_specs then server_specs = resolve_config().servers or {} end |
| 53 | + for server, spec in pairs(server_specs) do |
| 54 | + M.register_server(server, spec) |
| 55 | + end |
| 56 | +end |
| 57 | + |
| 58 | +return M |
0 commit comments