diff --git a/lua/troy0820/lazy/lsp.lua b/lua/troy0820/lazy/lsp.lua index 956f451..7251aa1 100644 --- a/lua/troy0820/lazy/lsp.lua +++ b/lua/troy0820/lazy/lsp.lua @@ -18,6 +18,38 @@ return { lsp_zero.on_attach(function(client, bufnr) lsp_zero.default_keymaps({ buffer = bufnr }) end) + local buffer_autoformat = function(bufnr) + local group = 'lsp_autoformat' + vim.api.nvim_create_augroup(group, { clear = false }) + vim.api.nvim_clear_autocmds({ group = group, buffer = bufnr }) + + vim.api.nvim_create_autocmd('BufWritePre', { + buffer = bufnr, + group = group, + desc = 'LSP format on save', + callback = function() + -- note: do not enable async formatting + vim.lsp.buf.format({ async = false, timeout_ms = 10000 }) + end, + }) + end + + vim.api.nvim_create_autocmd('LspAttach', { + callback = function(event) + local id = vim.tbl_get(event, 'data', 'client_id') + local client = id and vim.lsp.get_client_by_id(id) + + if client == nil then + return + end + + -- make sure there is at least one client with formatting capabilities + if client.supports_method('textDocument/formatting') then + buffer_autoformat(event.buf) + end + end + }) + require('mason').setup({}) require('mason-lspconfig').setup({