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 and dbg.get() then
      vim.print('Format failed', 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 and dbg.get() then print('Using LSP formatter: ' .. 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' },
      zig      = { 'zigfmt' },
      markdown = { 'mdslw' },
      -- 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' },
    },
    formatters       = {
      mdslw = {
        prepend_args = { '--features', 'keep-linebreaks,collate-link-defs,outsource-inline-links', '--stdin-filepath', '$FILENAME' },
      },
    },
    log_level        = dbg.get() and vim.log.levels.TRACE or vim.log.levels.INFO,
  }
end)