From cfe2cb9ac9e9ab8a48da70cd1f436b49c74d8887 Mon Sep 17 00:00:00 2001 From: flea Date: Mon, 19 Feb 2024 18:48:54 +0800 Subject: [PATCH] Auto install formatter used by conform --- lua/custom/plugins/conform.lua | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/lua/custom/plugins/conform.lua b/lua/custom/plugins/conform.lua index 0e643ce6..239893b8 100644 --- a/lua/custom/plugins/conform.lua +++ b/lua/custom/plugins/conform.lua @@ -1,20 +1,35 @@ return { 'stevearc/conform.nvim', + dependencies = { + 'williamboman/mason.nvim', + }, event = { 'BufReadPre', 'BufNewFile' }, opts = { formatters_by_ft = { lua = { 'stylua' }, - python = function(bufnr) - if require('conform').get_formatter_info('ruff_format', bufnr).available then - return { 'ruff_format' } - else - return { 'isort', 'black' } - end - end, + python = { 'ruff_format' }, }, format_on_save = { timeout_ms = 500, lsp_fallback = true, }, }, + config = function(_, opts) + local registry = require 'mason-registry' + registry.refresh(function() + for _, tbl in pairs(opts.formatters_by_ft) do + for _, pkg_name in ipairs(tbl) do + -- TODO the name formatters_by_ft needed may be different from the name mason needed + if pkg_name == 'ruff_format' then + pkg_name = 'ruff' + end + local pkg = registry.get_package(pkg_name) + if not pkg:is_installed() then + pkg:install() + end + end + end + end) + require('conform').setup(opts) + end, }