通过nvim-config-local覆盖conform.nvim以停止对某些文件的自动格式化
我已经fork了 kickstart.nvim 并将其克隆到我的机器,同时还把 nvim-config-local 添加到了 require('lazy').setup(...) 部分的 ~/.config/nvim/init.lua。现在我想在一个项目目录中放置一个 .nvim.lua 文件,并且仅禁用Python文件的格式化,而不修改其他 conform 设置。如何在我的 .nvim.lua 中,仅扩展 formatters_by_ft 字段,使其在 conform 的配置中生效,而不覆盖设置的其他部分?
我通过直接修改整个 conform 设置来得到一个简单可行的解决方案,但这有点粗糙。这里是工作目录中 .nvim.lua 文件的一个片段,它实现了这个功能:
-- @file /path/to/project/.nvim.lua
print("Project .nvim.lua loaded") -- check :messages to verify loaded
require("conform").setup({formatters_by_ft = {python = {}}})
接着在 nvim 的 :ConformInfo 中显示,正如预期,没有可用的格式化程序。
另一种粗糙的做法只是把 conform 的设置从我的 init.lua 复制到 .nvim.lua,并修改 formatters_by_ft,但这看起来也不是正确的解决办法。
一个简单的最终解决方案是把 format_on_save 从 init.lua 中移除,然后在需要自动格式化时显式地调用 <leader>f。
这是我的 init.lua 文件供参考的片段:
-- @file ~/.config/nvim/init.lua
require('lazy').setup({
{
'klen/nvim-config-local',
config = function()
require('config-local').setup {
-- Config file patterns to load (lua supported)
config_files = { '.nvim.lua', '.nvimrc', '.exrc' },
-- Where the plugin keeps files data
hashfile = vim.fn.stdpath 'data' .. '/config-local',
autocommands_create = true, -- Create autocommands (VimEnter, DirectoryChanged)
commands_create = true, -- Create commands (ConfigLocalSource, ConfigLocalEdit, ConfigLocalTrust, ConfigLocalDeny)
silent = false, -- Disable plugin messages (Config loaded/denied)
lookup_parents = true, -- Lookup config files in parent directories
}
end,
},
{ -- Autoformat
'stevearc/conform.nvim',
event = { 'BufWritePre' },
cmd = { 'ConformInfo' },
keys = {
{
'<leader>f',
function()
require('conform').format { async = true, lsp_format = 'fallback' }
end,
mode = '',
desc = '[F]ormat buffer',
},
},
opts = {
notify_on_error = false,
format_on_save = function(bufnr)
-- Disable "format_on_save lsp_fallback" for languages that don't
-- have a well standardized coding style. You can add additional
-- languages here or re-enable it for the disabled ones.
local disable_filetypes = { c = false, cpp = false, cmake = true }
if disable_filetypes[vim.bo[bufnr].filetype] then
return nil
else
return {
timeout_ms = 500,
lsp_format = 'fallback',
}
end
end,
formatters_by_ft = {
lua = { 'stylua' },
python = { 'autopep8' },
cmake = {},
-- Conform can also run multiple formatters sequentially
-- python = { "isort", "black" },
--
-- You can use 'stop_after_first' to run the first available formatter from the list
-- javascript = { "prettierd", "prettier", stop_after_first = true },
},
formatters = {
clang_format = {
prepend_args = { '--style=file', '--fallback-style=LLVM' },
},
},
},
},
...
}
解决方案
-- @file /path/to/project/.nvim.lua
require("conform").formatters_by_ft.python = {}
require 简单地返回在 conform.nvim/lua/conform/init.lua 中定义的表,其中一个键是 formatters_by_ft。由于 .nvim.lua 在 lazy.nvim 之后初始化(请参阅问题中的 ~/.config/nvim/init.lua),.nvim.lua 可用于填充 conform 配置表中所需的字段。具体来说,可以在 formatters_by_ft 字段中的 python 字段填充一个空表。这会在目标项目中禁用Python的格式化,同时保持其他 conform 配置不变。