From 5aa08aef39dee438ddc3f58fd2e8d98185ebcd6f Mon Sep 17 00:00:00 2001 From: Sonny Bakker Date: Tue, 11 Feb 2025 09:10:52 +0100 Subject: [PATCH] Enable formatting on save Requires `ENABLE_FORMATTING` to be set --- templates/nvim/lua/lsp.lua.j2 | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/templates/nvim/lua/lsp.lua.j2 b/templates/nvim/lua/lsp.lua.j2 index a90237a..ad3fbbd 100644 --- a/templates/nvim/lua/lsp.lua.j2 +++ b/templates/nvim/lua/lsp.lua.j2 @@ -156,3 +156,28 @@ vim.diagnostic.config({ border = border }, }) + +local enable_formatting = os.getenv("ENABLE_FORMATTING", False) + +-- format buffers before saving for specific LSPs +if (enable_formatting) then + local excluded_clients = { 'pyright' } + + vim.api.nvim_create_autocmd('LspAttach', { + group = vim.api.nvim_create_augroup('lsp', { clear = true }), + callback = function(args) + vim.api.nvim_create_autocmd('BufWritePre', { + buffer = args.buf, + callback = function() + vim.lsp.buf.format { + filter = function(client) + return not vim.list_contains(excluded_clients, client.name) + end, + async = false, + id = args.data.client_id + } + end, + }) + end + }) +end