在输入快捷键格式化时触发检测是否安装格式化工具

This commit is contained in:
cap153 2025-02-12 14:07:22 +08:00 committed by GitHub
parent f3d14dd626
commit 30f47f2f87
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,42 +3,31 @@ return {
dependencies = {
"williamboman/mason.nvim",
},
event = { "BufWritePre" },
-- Customize or remove this keymap to your liking
keys = {
{
"<leader>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()
-- 设置 <leader>f 键映射,在按下时自动检测并安装缺失的工具后格式化代码
vim.keymap.set({ "n", "v" }, "<leader>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,
}