Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

neovim/lua/bugabinga/format.lua

Raw
local puk = require 'std.puk'
local dbg = require 'std.dbg'
local map = require 'std.map'
local user_command = require 'std.user_command'

local conform = puk 'conform'

local format = function ( async )
	conform.format( {
		async = async,
		lsp_format = 'fallback',
	}, function ( err )
		if err then
			dbg( 'Format failed %s', err )
		end
	end )
end

local format_sync = function ()
	format( false )
end

local format_async = function ()
	format( true )
end

map.N {
	description = 'Format buffer',
	category = 'format',
	keys = '<leader>=',
	command = format_async,
}

user_command.Format 'Format the current buffer asynchronously' ( format_async )
user_command.FormatSync 'Format the current buffer' ( format_sync )

vim.o.formatexpr = "v:lua.require'conform'.formatexpr()"

conform.setup {
	formatters = {
		-- lenient JSON parsing so formatting repairs trailing commas instead of
		-- refusing; applies to every repo, no biome.json needed. append_args keeps
		-- the builtin args ($FILENAME, indent fallback) untouched
		biome = {
			append_args = { '--json-parse-allow-trailing-commas=true' },
		},
		sqruff = {
			command = 'sqruff',
			args = { 'fix', '-' },
			stdin = true,
		},
	},
	formatters_by_ft = {
		toml              = { 'taplo' },
		sh                = { 'shfmt' },
		just              = { 'just' },
		go                = { 'goimports', 'gofmt' },
		kdl               = { 'kdlfmt' },
		nu                = { 'nufmt' },
		qml               = { 'qmlformat' },
		sql               = { 'sqruff' },
		d2                = { 'd2' },
		markdown          = { 'dprint', 'injected' },
		['markdown.mdx']  = { 'injected' },
		html              = { 'biome' },
		javascript        = { 'biome' },
		javascriptreact   = { 'biome' },
		typescript        = { 'biome' },
		typescriptreact   = { 'biome' },
		json              = { 'biome' },
		jsonc             = { 'biome' },
		-- jsonl must never be rewritten by a JSON formatter (one object per line)
		jsonl             = {},
		python            = { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' },
		sass              = { 'deno_fmt' },
		-- Use the “_” file type to run formatters on file types that don't
		-- have other formatters configured.
		['_']             = { 'trim_whitespace', 'trim_newlines' },
	},
	log_level = dbg.get() and vim.log.levels.TRACE or vim.log.levels.ERROR,
}