Skip to content

[idea] Conform format-on-save: BufWritePre autocmd with per-buffer opt-out toggle #147

@stanfish06

Description

@stanfish06

What

Add an optional auto-format-on-save behaviour driven by a BufWritePre autocmd that calls conform.format(). Pair it with a buffer-local toggle (<leader>lF) so it can be disabled per-buffer when format noise is unwanted (e.g. exploring a poorly-formatted third-party file).

Where

lua/config/plugin_config.lua — inside the if conform_ok and not is_vscode then block, alongside the existing <leader>lf keymap (lines 152–163).

Why it matters

The config already has <leader>lf for manual format. Auto-format-on-save is the natural next step: it eliminates the manual step for files where a formatter is configured and produces clean commits without requiring discipline. The per-buffer toggle handles the cases where you don't want it (reading upstream code, pairing sessions, etc.).

Suggested implementation

-- inside the conform_ok block:
local auto_format_enabled = true  -- global default

vim.keymap.set("n", "<leader>lF", function()
    vim.b.auto_format = not vim.b.auto_format  -- nil → false (disable)
    local state = vim.b.auto_format == false and "OFF" or "ON"
    vim.notify("Auto-format: " .. state, vim.log.levels.INFO)
end, { desc = "Toggle auto-format for buffer" })

vim.api.nvim_create_autocmd("BufWritePre", {
    callback = function()
        -- skip if explicitly disabled for this buffer
        if vim.b.auto_format == false then return end
        if not auto_format_enabled then return end
        conform.format({ timeout_ms = 500, lsp_format = "fallback" })
    end,
})

Notes

  • The timeout_ms cap prevents slow formatters from blocking the write.
  • lsp_format = "fallback" means the LSP formatter fires when no conform formatter is configured for the filetype, consistent with the existing default_format_opts in the conform setup.
  • A global toggle (auto_format_enabled) can be added later if needed; the per-buffer flag covers the common case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions