Files
nvim-config/lua/plugins/formatting.lua

138 lines
3.7 KiB
Lua

-- Formatting configuration with conform.nvim
-- Autoformat on save with per-filetype formatters
return {
{
"stevearc/conform.nvim",
event = { "BufWritePre" },
cmd = { "ConformInfo" },
keys = {
{
"<leader>cf",
function()
require("conform").format({ async = true, lsp_fallback = true })
end,
mode = { "n", "v" },
desc = "Format buffer",
},
},
opts = {
-- Formatters by filetype
formatters_by_ft = {
-- Go
go = { "gofumpt", "goimports" },
-- Lua
lua = { "stylua" },
-- JavaScript/TypeScript
javascript = { "prettier" },
javascriptreact = { "prettier" },
typescript = { "prettier" },
typescriptreact = { "prettier" },
-- Web
html = { "prettier" },
css = { "prettier" },
scss = { "prettier" },
-- Data formats
json = { "prettier" },
jsonc = { "prettier" },
yaml = { "prettier" },
-- Markdown
markdown = { "prettier" },
["markdown.mdx"] = { "prettier" },
-- SQL
sql = { "sql_formatter", "sqlfluff", "pg_format" },
mysql = { "sql_formatter", "sqlfluff" },
plsql = { "sql_formatter", "sqlfluff", "pg_format" },
-- Makefile (no formatter - they require tabs)
-- make = {},
-- Fallback for all other filetypes
["_"] = { "trim_whitespace" },
},
-- Format on save
format_on_save = function(bufnr)
-- Disable for certain filetypes
local ignore_filetypes = { "sql", "mysql", "plsql" }
if vim.tbl_contains(ignore_filetypes, vim.bo[bufnr].filetype) then
return
end
-- Disable with a global or buffer-local variable
if vim.g.disable_autoformat or vim.b[bufnr].disable_autoformat then
return
end
return {
timeout_ms = 3000,
lsp_fallback = true,
}
end,
-- Formatter options
formatters = {
-- Stylua configuration
stylua = {
prepend_args = { "--indent-type", "Spaces", "--indent-width", "2" },
},
-- Prettier configuration
prettier = {
prepend_args = { "--tab-width", "2", "--single-quote" },
},
-- SQL formatter configuration
sql_formatter = {
prepend_args = { "--language", "postgresql" },
},
-- goimports configuration
goimports = {
prepend_args = { "-local", "github.com" },
},
},
},
init = function()
-- Commands to toggle format on save
vim.api.nvim_create_user_command("FormatDisable", function(args)
if args.bang then
-- FormatDisable! will disable formatting just for this buffer
vim.b.disable_autoformat = true
else
vim.g.disable_autoformat = true
end
vim.notify("Autoformat disabled", vim.log.levels.INFO)
end, {
desc = "Disable autoformat-on-save",
bang = true,
})
vim.api.nvim_create_user_command("FormatEnable", function()
vim.b.disable_autoformat = false
vim.g.disable_autoformat = false
vim.notify("Autoformat enabled", vim.log.levels.INFO)
end, {
desc = "Re-enable autoformat-on-save",
})
vim.api.nvim_create_user_command("FormatToggle", function()
vim.g.disable_autoformat = not vim.g.disable_autoformat
if vim.g.disable_autoformat then
vim.notify("Autoformat disabled", vim.log.levels.INFO)
else
vim.notify("Autoformat enabled", vim.log.levels.INFO)
end
end, {
desc = "Toggle autoformat-on-save",
})
end,
},
}