From a6da22da4a22944706d236cd4d40ccb1bd516cc5 Mon Sep 17 00:00:00 2001 From: cap153 <67049883+cap153@users.noreply.github.com> Date: Sun, 9 Feb 2025 22:42:35 +0800 Subject: [PATCH] Create formatter.lua --- lua/lazy/plugins/formatter.lua | 64 ++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 lua/lazy/plugins/formatter.lua diff --git a/lua/lazy/plugins/formatter.lua b/lua/lazy/plugins/formatter.lua new file mode 100644 index 0000000..c48c92c --- /dev/null +++ b/lua/lazy/plugins/formatter.lua @@ -0,0 +1,64 @@ +return { + "stevearc/conform.nvim", + 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" }, + }, + }, + config = function(_, opts) + -- 初始化 mason.nvim + require("mason").setup() + + -- 辅助函数:从 formatters_by_ft 中提取所有工具名称(去重) + local function get_ensure_installed(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 + end + elseif type(cfg) == "string" then + tools[cfg] = true + end + end + local list = {} + for tool, _ in pairs(tools) do + table.insert(list, tool) + end + 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() + end + end + + -- 最后调用 conform.nvim 的 setup,使用传入的 opts + require("conform").setup(opts) + end, +}