nvim/lua/plugins/conform.lua

109 lines
3.2 KiB
Lua

-- conform.nvim: Modern formatting without LSP overhead
-- Replaces none-ls for all formatting tasks
return {
"stevearc/conform.nvim",
event = { "BufReadPre", "BufNewFile" },
config = function()
local conform = require("conform")
-- Helper: Find project-local executable, fallback to global
-- Searches node_modules/.bin/, vendor/bin/, and Mason bin first
local function find_executable(names)
local cwd = vim.fn.getcwd()
local mason_bin = vim.fn.stdpath("data") .. "/mason/bin/"
local search_paths = {
cwd .. "/node_modules/.bin/",
cwd .. "/vendor/bin/",
mason_bin,
}
for _, name in ipairs(names) do
for _, path in ipairs(search_paths) do
local full_path = path .. name
if vim.fn.executable(full_path) == 1 then
return full_path
end
end
if vim.fn.executable(name) == 1 then
return name
end
end
return nil
end
conform.setup({
formatters_by_ft = {
-- JavaScript, TypeScript, CSS, SCSS, JSON, HTML, Markdown
javascript = { "prettier" },
javascriptreact = { "prettier" },
typescript = { "prettier" },
typescriptreact = { "prettier" },
css = { "prettier" },
scss = { "prettier" },
html = { "prettier" },
json = { "prettier" },
jsonc = { "prettier" },
markdown = { "prettier" },
-- PHP
php = { "phpcbf" },
-- Lua
lua = { "stylua" },
},
-- Custom formatter definitions with executable resolution
formatters = {
prettier = {
command = find_executable({ "prettier" }) or "prettier",
},
phpcbf = {
-- Extend built-in phpcbf to add WordPress standard
prepend_args = { "--standard=WordPress" },
},
stylua = {
command = find_executable({ "stylua" }) or "stylua",
},
},
-- Format on save
format_on_save = function(bufnr)
-- Check global flag
if vim.g.format_on_save == false then
return nil
end
return {
timeout_ms = 500,
lsp_fallback = false, -- Don't use LSP formatting
}
end,
})
-- Format-on-save is enabled by default
vim.g.format_on_save = true
-- Keymaps
-- Toggle format-on-save
vim.keymap.set("n", "<leader>lt", function()
vim.g.format_on_save = not vim.g.format_on_save
local status = vim.g.format_on_save and "enabled" or "disabled"
vim.notify("Format on save " .. status, vim.log.levels.INFO)
end, { desc = "Formatting: Toggle format on save", silent = true, noremap = true })
-- Manual format (buffer)
vim.keymap.set("n", "<leader>lf", function()
conform.format({ async = false, lsp_fallback = false })
end, { desc = "Formatting: Format buffer", silent = true, noremap = true })
-- Manual format (visual range)
vim.keymap.set("v", "<leader>lf", function()
conform.format({ async = false, lsp_fallback = false })
end, { desc = "Formatting: Format selection", silent = true, noremap = true })
end,
}