diff --git a/lua/lazy/plugins/formatter.lua b/lua/lazy/plugins/formatter.lua index c48c92c..c885837 100644 --- a/lua/lazy/plugins/formatter.lua +++ b/lua/lazy/plugins/formatter.lua @@ -3,42 +3,31 @@ return { dependencies = { "williamboman/mason.nvim", }, - event = { "BufWritePre" }, - -- Customize or remove this keymap to your liking - keys = { - { - "f", - function() - require("conform").format({ async = true }) - end, - mode = "", - desc = "格式化代码", - }, - }, opts = { formatters_by_ft = { lua = { "stylua" }, python = { "isort", "black" }, - rust = { "rustfmt", lsp_format = "fallback" }, + rust = { "rust-analyzer", lsp_format = "fallback" }, + toml = { "templ" }, }, }, config = function(_, opts) - -- 初始化 mason.nvim + -- 初始化 mason.nvim 和 conform.nvim require("mason").setup() + require("conform").setup(opts) - -- 辅助函数:从 formatters_by_ft 中提取所有工具名称(去重) - local function get_ensure_installed(ft_table) + -- 辅助函数:从指定文件类型的配置中提取所有工具名称(去重) + local function get_ensure_installed_for_ft(ft, ft_table) local tools = {} - for _, cfg in pairs(ft_table) do - if type(cfg) == "table" then - for _, item in ipairs(cfg) do - if type(item) == "string" then - tools[item] = true - end + local cfg = ft_table[ft] + if type(cfg) == "table" then + for _, item in ipairs(cfg) do + if type(item) == "string" then + tools[item] = true end - elseif type(cfg) == "string" then - tools[cfg] = true end + elseif type(cfg) == "string" then + tools[cfg] = true end local list = {} for tool, _ in pairs(tools) do @@ -47,18 +36,18 @@ return { return list end - local ensure_installed = get_ensure_installed(opts.formatters_by_ft) - - -- 利用 mason 的注册中心自动安装缺失的工具 - local registry = require("mason-registry") - for _, tool in ipairs(ensure_installed) do - if not registry.is_installed(tool) then - vim.notify("Installing formatter: " .. tool, vim.log.levels.INFO) - registry.get_package(tool):install() + -- 设置 f 键映射,在按下时自动检测并安装缺失的工具后格式化代码 + vim.keymap.set({ "n", "v" }, "f", function() + local ft = vim.bo.filetype + local tools = get_ensure_installed_for_ft(ft, opts.formatters_by_ft) + local registry = require("mason-registry") + for _, tool in ipairs(tools) do + if not registry.is_installed(tool) then + vim.notify("Installing formatter: " .. tool, vim.log.levels.INFO) + registry.get_package(tool):install() + end end - end - - -- 最后调用 conform.nvim 的 setup,使用传入的 opts - require("conform").setup(opts) + require("conform").format({ async = true, lsp_fallback = true }) + end, { desc = "格式化代码(检测安装缺失工具)" }) end, }