Enable formatter for explicit use only
MoritzBoehme opened this issue · 5 comments
Hey, I was wondering if there is a possibility to enable a formatter for explicit use only.
For example if I want to format a nix file I want to use nixpkgs-fmt as the default, but only sometimes I want to use alejandra (not always, as it is more opinionated than the default formatter).
In the cases where I want to use the non default formatter, my ideal usage would just be to call :Format alejandra
. When calling :Format
on a nix file it would ideally ignore alejandra, because I didn't explicitly choose it.
Is this or something alike possible?
Could I perhaps wrap the default config for alejandra to detect if it was called explicitly?
You can use something like this:
vim.api.nvim_create_user_command("Fmt", function(opts)
local params = vim.split(opts.args, "%s+", { trimempty = true })
vim.cmd("set filetype=" .. params[1] .. " | :Format")
end, {
bang = true,
nargs = 1,
complete = function()
return { "json", "xml", "yaml" }
end,
})
example usage: :Fmt json
Maybe I could just add a new file type with the name "alejandra" and then use your function to format the current file with this. And using the completion maybe I could even make it smarter such that nix files get only the completion options for the fake formatter languages for nix.
I'll try this and update as soon as possible.
Great, this works well enough.
For anyone wanting to replicate this:
require("formatter").setup({
filetype = {
-- HACK to use specific formatters only when specified
alejandra = {
require("formatter.filetypes.nix").alejandra,
},
},
})
vim.api.nvim_create_user_command("Fmt", function(opts)
local params = vim.split(opts.args, "%s+", { trimempty = true })
local filetype = vim.bo.filetype
vim.cmd("set filetype=" .. params[1]) -- fake filetype
vim.cmd(":Format")
vim.cmd("set filetype=" .. filetype) -- restore original filetype
end, {
nargs = 1,
complete = function()
local languages = {
nix = { "alejandra" },
}
return languages[vim.bo.filetype] or {}
end,
})
Thanks for sharing your solution.
Considering this works well enough for me, I think this issue is closed.