From 4cb90679a218562444869c27287d952cbe173361 Mon Sep 17 00:00:00 2001 From: Pim Kunis Date: Mon, 28 Oct 2024 13:02:12 +0100 Subject: [PATCH] Run treefmt on nvim buffer save --- home-manager/neovim/lspconfig.lua | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/home-manager/neovim/lspconfig.lua b/home-manager/neovim/lspconfig.lua index 603e6a1..c043d61 100644 --- a/home-manager/neovim/lspconfig.lua +++ b/home-manager/neovim/lspconfig.lua @@ -45,14 +45,21 @@ require("lspconfig").terraformls.setup({ capabilities = capabilities, }) --- require'lspconfig'.efm.setup { --- on_attach = require("lsp-format").on_attach, --- init_options = {documentFormatting = true}, --- settings = { --- languages = { --- lua = {{formatCommand = "lua-format -i", formatStdin = true}}, --- nix = {{formatCommand = "nixfmt", formatStdin = true}} --- } --- }, --- filetypes = {"lua", "nix"} --- } +local function has_treefmt() + local git_root = vim.fn.systemlist("git rev-parse --show-toplevel")[1] + if vim.v.shell_error ~= 0 then + return false + end + local treefmt_path = git_root .. "/treefmt.nix" + return vim.fn.filereadable(treefmt_path) == 1 +end + +vim.api.nvim_create_autocmd("BufWritePost", { + pattern = "*", + callback = function() + if has_treefmt() then + vim.cmd("silent !treefmt > /dev/null 2>&1") + end + end, + group = vim.api.nvim_create_augroup("TreefmtAutoformat", { clear = true }), +})