local autoformat_files = '*.py,*.rs,*.tf'

local common_on_attach = function(client, bufnr)
    -- Autoformat on save.
    if client:supports_method("textDocument/formatting") then
        vim.api.nvim_create_autocmd("BufWritePre", {
            pattern = autoformat_files,
            callback = function()
                vim.lsp.buf.format()
            end,
        })
    end

    -- Use vim's default coloring.
    --client.server_capabilities.semanticTokensProvider = nil
    --for _, group in ipairs(vim.fn.getcompletion("@lsp", "highlight")) do
    --    vim.api.nvim_set_hl(0, group, {})
    --end
end

-- LSP diagnostics.
vim.lsp.handlers["textDocument/publishDiagnostics"] =
    vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, {
        virtual_text = false,
        underline = true,
        signs = true,
        update_in_insert = false
    })

vim.g.rustaceanvim = function()
    return {
        -- Plugin configuration.
        tools = {
        },
        -- LSP configuration.
        server = {
            on_attach = function(client, bufnr)
                common_on_attach(client, bufnr)
            end,
            default_settings = {
                -- rust-analyzer language server configuration
                ['rust-analyzer'] = {
                    imports = {
                        granularity = {
                            group = "module",
                        },
                        prefix = "self",
                    },
                    cargo = {
                        buildScripts = {
                            enable = true,
                        },
                    },
                    procMacro = {
                        enable = true
                    },
                    checkOnSave = true,
                },
            },
            -- DAP configuration.
            dap = {
            },
        }
    }
end

local capabilities = vim.lsp.protocol.make_client_capabilities()

vim.lsp.enable('ty')

local servers = {
    "clangd",
    "lua_ls",
    "ocamllsp",
    "rnix",
    "terraformls",
    "vimls",
}
for _, lsp in ipairs(servers) do
    vim.lsp.config(lsp, {
        capabilities = capabilities,
        on_attach = common_on_attach,
    })
end
