repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

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 format = function ()
	require 'conform'.format( { async = false }, function ( err )
		if err then
			dbg( 'Format failed %s', err )
		end
	end )

	vim.lsp.buf.format {
		filter = function ( client )
			local ok = client:supports_method 'textDocument/formatting' ---@diagnostic disable-line: param-type-mismatch, missing-parameter
			if ok then dbg( 'Using LSP formatter: %s', client.name ) end
			return ok
		end,
		async = false,
	}
end

map.N {
	description = 'Format buffer',
	category = 'format',
	keys = '=',
	command = format,
}

user_command.Format 'Format the current buffer' ( format )

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

puk.defer 'conform' ( function ( conform )
	conform.setup {
		formatters_by_ft = {
			toml       = { 'taplo' },
			sh         = { 'shfmt' },
			just       = { 'just' },
			d2         = { 'd2_fmt' },
			markdown   = { 'deno_fmt' },
			javascript = { 'deno_fmt' },
			typescript = { 'deno_fmt' },
			json       = { 'deno_fmt' },
			-- Use the “*” file type to run formatters on all file types.
			['*']      = { 'injected', 'typos' },
			-- 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,
	}
end )