Skip to content

[idea] Auto-save on FocusLost — silent write for named modified buffers #302

Description

@stanfish06

What

Add a FocusLost autocmd that silently writes all named, modified, normal buffers when Neovim loses focus (e.g. switching to the terminal, browser, or another app).

Where

lua/config/options.lua — alongside the existing autoread = true setting (line 71) which already handles the incoming side of auto-sync.

Why it matters

autoread = true reloads files changed on disk, but only when Neovim is focused. There's no corresponding outward auto-save, so edits made in Neovim can be lost if the user switches away before pressing :w. This is especially relevant given the workflow described in init.lua: the user runs LSP clients, formatters, and terminal processes that often read the same files. Enabling auto-save on focus loss completes the round-trip.

Recommended implementation

vim.api.nvim_create_autocmd("FocusLost", {
    callback = function()
        for _, buf in ipairs(vim.api.nvim_list_bufs()) do
            if vim.bo[buf].modified
                and vim.bo[buf].buftype == ""
                and vim.api.nvim_buf_get_name(buf) ~= ""
                and vim.bo[buf].modifiable
            then
                pcall(vim.api.nvim_buf_call, buf, function()
                    vim.cmd("silent! write")
                end)
            end
        end
    end,
})

Conditions: buftype == "" (normal file, not terminal/quickfix/nofile), non-empty name, modifiable, and modified. The pcall guards against readonly filesystems or permission errors without surfacing a message.

Trade-offs

  • Writes happen on every focus loss, so the file on disk always reflects the buffer state — formatters and linters (shellcheck, ruff) that watch the file will re-trigger. This is usually desirable given the existing nvim-lint BufWritePost triggers.
  • Does not affect terminal buffers, quickfix, or scratch buffers.
  • Can be toggled by removing the autocmd or gating it behind a vim.g.auto_save flag if opt-in is preferred.

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